-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathjson.go
33 lines (29 loc) · 822 Bytes
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package nano
import (
"encoding/json"
"io"
"net/http"
"reflect"
)
// BindJSON is functions to bind request body (with contet type application/json) to targetStruct.
// targetStruct must be pointer to user defined struct.
func BindJSON(r *http.Request, targetStruct interface{}) *BindingError {
// only accept pointer
if reflect.TypeOf(targetStruct).Kind() != reflect.Ptr {
return &BindingError{
Message: "expected pointer to target struct, got non-pointer",
HTTPStatusCode: http.StatusInternalServerError,
}
}
if r.Body != nil {
defer r.Body.Close()
err := json.NewDecoder(r.Body).Decode(targetStruct)
if err != nil && err != io.EOF {
return &BindingError{
Message: err.Error(),
HTTPStatusCode: http.StatusBadRequest,
}
}
}
return ValidateStruct(targetStruct)
}