-
if i write a response in handler like this,
this is how it'd be look like.
is there any middleware or options that i can format or pre-process the body of the response returned from handler before it is being sent to the client using echo like below?
i'm new to both go and echo and hope this question doesn't look too silly. thank you in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
It depends mostly what behavior this response "container" should have. Does that What you are looking for is JSON marshalling and struct tags + some helper function. You can make that import (
"github.com/labstack/echo/v4"
"net/http"
)
func main() {
e := echo.New()
e.GET("/", func(ctx echo.Context) error {
type dataDTO struct {
Go string `json:"go"`
}
type responseDTO = struct {
Size int64 `json:"size"`
ExtraInfo map[string]string `json:"extraInfo"`
Data dataDTO `json:"data"`
}
resp := responseDTO{
Size: 999,
ExtraInfo: map[string]string{
"key": "value",
},
Data: dataDTO{
Go: "echo",
},
}
return ctx.JSON(http.StatusOK, resp)
})
if err := e.Start(":8080"); err != http.ErrServerClosed {
e.Logger.Fatal(err)
}
} |
Beta Was this translation helpful? Give feedback.
It depends mostly what behavior this response "container" should have. Does that
size
field must be size of bytes ofdata
field? IsextraInfo
some arbitrary map of something?What you are looking for is JSON marshalling and struct tags + some helper function. You can make that
responseDTO.Data
field to be of typeinterface{}
and for each handler set your handler specific struct there (having tags for json fields)