48 lines
952 B
Go
48 lines
952 B
Go
package envitron
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
|
|
"github.com/labstack/echo"
|
|
)
|
|
|
|
type jsonError struct {
|
|
Message string `json:"error"`
|
|
}
|
|
|
|
func (e jsonError) Error() string {
|
|
return e.Message
|
|
}
|
|
|
|
type bindError struct {
|
|
Message string `json:"error"`
|
|
Offset int64 `json:"offset"`
|
|
Field string `json:"field,omitempty"`
|
|
}
|
|
|
|
func (e bindError) Error() string {
|
|
return e.Message
|
|
}
|
|
|
|
type jsonBinder struct{}
|
|
|
|
func (b jsonBinder) Bind(i interface{}, c echo.Context) error {
|
|
err := json.NewDecoder(c.Request().Body).Decode(i)
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
|
|
switch e := err.(type) {
|
|
case *json.SyntaxError:
|
|
return bindError{Message: `Syntax error`, Offset: e.Offset, Field: ``}
|
|
case *json.UnmarshalTypeError:
|
|
return bindError{Message: `Type error`, Offset: e.Offset, Field: e.Field}
|
|
}
|
|
|
|
if err == io.ErrUnexpectedEOF || err == io.EOF {
|
|
return jsonError{`Unexpected EOF`}
|
|
}
|
|
return jsonError{`Unknown error occurred while parsing JSON`}
|
|
}
|