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
1 changed files with 30 additions and 28 deletions

58
main.go
View File

@ -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)
}