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

20
main.go
View file

@ -1,7 +1,6 @@
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
@ -18,6 +17,10 @@ var version = "dev"
func main() {
app := &cli.App{
Commands: []*cli.Command{
{
Name: "serve",
Aliases: []string{"c"},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "listen",
@ -40,10 +43,6 @@ func main() {
Value: ".",
},
},
Commands: []*cli.Command{
{
Name: "serve",
Aliases: []string{"c"},
Usage: "complete a task on the list",
Action: func(ctx *cli.Context) error {
listen := ctx.String("listen")
@ -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)
}