Use faster JSON and gzip packages

This commit is contained in:
Ingo Oppermann
2024-04-24 15:42:11 +02:00
parent 38fa6159e3
commit 03da97217b
178 changed files with 62194 additions and 92 deletions

View File

@@ -21,6 +21,7 @@ import (
"strings"
"github.com/datarhei/core/v16/cluster/client"
"github.com/datarhei/core/v16/encoding/json"
"github.com/datarhei/core/v16/http/handler/util"
httplog "github.com/datarhei/core/v16/http/log"
mwlog "github.com/datarhei/core/v16/http/middleware/log"
@@ -73,7 +74,7 @@ func NewAPI(config APIConfig) (API, error) {
a.address = address
a.router = echo.New()
a.router.Debug = true
a.router.JSONSerializer = &GoJSONSerializer{}
a.router.HTTPErrorHandler = ErrorHandler
a.router.Validator = validator.New()
a.router.HideBanner = true
@@ -965,3 +966,27 @@ func ErrorHandler(err error, c echo.Context) {
}
}
}
// GoJSONSerializer implements JSON encoding using encoding/json.
type GoJSONSerializer struct{}
// Serialize converts an interface into a json and writes it to the response.
// You can optionally use the indent parameter to produce pretty JSONs.
func (d GoJSONSerializer) Serialize(c echo.Context, i interface{}, indent string) error {
enc := json.NewEncoder(c.Response())
if indent != "" {
enc.SetIndent("", indent)
}
return enc.Encode(i)
}
// Deserialize reads a JSON from a request body and converts it into an interface.
func (d GoJSONSerializer) Deserialize(c echo.Context, i interface{}) error {
err := json.NewDecoder(c.Request().Body).Decode(i)
if ute, ok := err.(*json.UnmarshalTypeError); ok {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", ute.Type, ute.Value, ute.Field, ute.Offset)).SetInternal(err)
} else if se, ok := err.(*json.SyntaxError); ok {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", se.Offset, se.Error())).SetInternal(err)
}
return err
}