2019-10-07 18:21:26 +05:00
|
|
|
package httpserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
)
|
|
|
|
|
|
|
|
// StrictJSONBinder implements Binder interface for Echo. It will parse
|
|
|
|
// JSON in strict mode throwing errors on schema mismatches.
|
|
|
|
type StrictJSONBinder struct{}
|
|
|
|
|
|
|
|
// Bind parses JSON input.
|
2021-11-20 23:06:40 +05:00
|
|
|
func (sjb *StrictJSONBinder) Bind(data interface{}, c echo.Context) error {
|
2019-10-07 18:21:26 +05:00
|
|
|
req := c.Request()
|
|
|
|
if req.ContentLength == 0 {
|
|
|
|
return echo.NewHTTPError(http.StatusBadRequest, "Request body can't be empty")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Decode it.
|
|
|
|
decoder := json.NewDecoder(req.Body)
|
|
|
|
decoder.DisallowUnknownFields()
|
2019-10-16 23:32:21 +05:00
|
|
|
|
2021-11-20 23:06:40 +05:00
|
|
|
// ToDo: rework this code.
|
|
|
|
// nolint:errorlint
|
|
|
|
if err := decoder.Decode(data); err != nil {
|
2019-10-07 18:21:26 +05:00
|
|
|
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))
|
|
|
|
} 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()))
|
|
|
|
} else {
|
|
|
|
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|