use echo methods to return json

This commit is contained in:
Simon Vieille 2022-08-22 00:12:24 +02:00
parent e1626e73f7
commit dd1739628f
Signed by: deblan
GPG key ID: 579388D585F70417

58
main.go
View file

@ -1,7 +1,6 @@
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
@ -18,33 +17,33 @@ var version = "dev"
func main() { func main() {
app := &cli.App{ 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{ Commands: []*cli.Command{
{ {
Name: "serve", Name: "serve",
Aliases: []string{"c"}, 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 { Action: func(ctx *cli.Context) error {
listen := ctx.String("listen") listen := ctx.String("listen")
port := ctx.Int64("port") port := ctx.Int64("port")
@ -77,6 +76,10 @@ type File struct {
Url string `json:"url"` Url string `json:"url"`
} }
type InternalError struct {
Error string `json:"error"`
}
func apiList(ctx echo.Context, directory, url string) error { func apiList(ctx echo.Context, directory, url string) error {
files := []File{} files := []File{}
@ -98,11 +101,10 @@ func apiList(ctx echo.Context, directory, url string) error {
return nil return nil
}) })
if err != 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.JSON(http.StatusOK, files)
return ctx.String(http.StatusOK, string(data))
} }