From dd1739628fb3d3866fbbbfbca492778ff5a14c5b Mon Sep 17 00:00:00 2001 From: Simon Vieille Date: Mon, 22 Aug 2022 00:12:24 +0200 Subject: [PATCH] use echo methods to return json --- main.go | 58 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/main.go b/main.go index d470b49..c73aac5 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,6 @@ package main import ( - "encoding/json" "fmt" "net/http" "os" @@ -18,33 +17,33 @@ var version = "dev" func main() { app := &cli.App{ - Flags: []cli.Flag{ - &cli.StringFlag{ - Name: "listen", - Aliases: []string{"l"}, - Value: "127.0.0.1", - }, - &cli.StringFlag{ - Name: "port", - Aliases: []string{"p"}, - Value: "4000", - }, - &cli.StringFlag{ - Name: "api-url", - Aliases: []string{"u"}, - Value: "http://127.0.0.1:4000", - }, - &cli.StringFlag{ - Name: "directory", - Aliases: []string{"d"}, - Value: ".", - }, - }, Commands: []*cli.Command{ { Name: "serve", Aliases: []string{"c"}, - Usage: "complete a task on the list", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "listen", + Aliases: []string{"l"}, + Value: "127.0.0.1", + }, + &cli.StringFlag{ + Name: "port", + Aliases: []string{"p"}, + Value: "4000", + }, + &cli.StringFlag{ + Name: "api-url", + Aliases: []string{"u"}, + Value: "http://127.0.0.1:4000", + }, + &cli.StringFlag{ + Name: "directory", + Aliases: []string{"d"}, + Value: ".", + }, + }, + Usage: "complete a task on the list", Action: func(ctx *cli.Context) error { listen := ctx.String("listen") port := ctx.Int64("port") @@ -77,6 +76,10 @@ type File struct { Url string `json:"url"` } +type InternalError struct { + Error string `json:"error"` +} + func apiList(ctx echo.Context, directory, url string) error { files := []File{} @@ -98,11 +101,10 @@ func apiList(ctx echo.Context, directory, url string) error { return nil }) + if err != nil { - return ctx.String(http.StatusInternalServerError, fmt.Sprintf("{\"error\":\"%s\"", err)) + return ctx.JSON(http.StatusInternalServerError, InternalError{Error: fmt.Sprintf("%s", err)}) } - data, _ := json.MarshalIndent(files, "", " ") - - return ctx.String(http.StatusOK, string(data)) + return ctx.JSON(http.StatusOK, files) }