timon_playgroud/tools/responses.go

131 lines
2.5 KiB
Go

package tools
import (
"net/http"
"github.com/labstack/echo/v4"
"gitlab.com/revoluterra-dev/common/helpers/trace"
)
type Response struct {
Error string `json:"error"`
Result interface{} `json:"result"`
Total int64 `json:"total"`
}
// // Serve422 generates 422 (wrong entity) error to response json.
func ServeError(c echo.Context, err error) error {
return c.JSON(
http.StatusUnprocessableEntity,
Response{
Error: trace.UnTrace(err).Error(),
Result: []struct{}{},
},
)
}
func ServeErrorMsg(c echo.Context, errorMessage string) error {
return c.JSON(
http.StatusUnprocessableEntity,
Response{
Error: errorMessage,
Result: []struct{}{},
},
)
}
// Serve404 generates 404 (not found) error to response json.
func Serve404(c echo.Context) error {
return c.JSON(
http.StatusNotFound,
Response{
Error: http.StatusText(http.StatusNotFound),
Result: []struct{}{},
},
)
}
func Serve405(c echo.Context) error {
return c.JSON(
http.StatusMethodNotAllowed,
Response{
Error: http.StatusText(http.StatusMethodNotAllowed),
Result: []struct{}{},
},
)
}
// Serve404 generates 401 (not found) error to response json.
func Serve401(c echo.Context) error {
return c.JSON(
http.StatusUnauthorized,
Response{
Error: http.StatusText(http.StatusUnauthorized),
Result: []struct{}{},
},
)
}
func Serve403(c echo.Context) error {
return c.JSON(
http.StatusForbidden,
Response{
Error: http.StatusText(http.StatusForbidden),
Result: []struct{}{},
},
)
}
func Serve429(c echo.Context) error {
return c.JSON(
http.StatusTooManyRequests,
Response{
Error: http.StatusText(http.StatusTooManyRequests),
Result: []struct{}{},
},
)
}
// Serve500 generates 500 (internal error) error to response json.
func Serve500(c echo.Context) error {
return c.JSON(
http.StatusInternalServerError,
Response{
Error: http.StatusText(http.StatusInternalServerError),
Result: []struct{}{},
},
)
}
func Serve503(c echo.Context) error {
return c.JSON(
http.StatusServiceUnavailable,
Response{
Error: "Server is restarting",
Result: []struct{}{},
},
)
}
func ServeData(c echo.Context, data interface{}, total ...int64) error {
var t int64
if len(total) > 0 {
t = total[0]
}
return c.JSON(
http.StatusOK,
Response{
Result: data,
Total: t,
},
)
}
// func usePath(e *echo.Echo, path string) string {
// e.OPTIONS(path, noContent)
// return path
// }
// func noContent(c echo.Context) error {
// return c.NoContent(200)
// }