-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.go
71 lines (58 loc) · 1.76 KB
/
request.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package binding
import (
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"github.com/gocraft/web"
)
var ErrRequestBodyIncomplete = fmt.Errorf("Request body is empty")
func decodeBodyToJSON(ctx interface{}, fieldType reflect.Type, r *web.Request) error {
t := reflect.ValueOf(ctx)
if t.Type().Kind() != reflect.Ptr {
panic("expected pointer to struct")
}
t = t.Elem()
const contextFieldNameForRequest = "RequestJSON"
saveToField := t.FieldByName(contextFieldNameForRequest)
if !saveToField.IsValid() {
panic(fmt.Sprintf("Expected to find field named %q name on the context", contextFieldNameForRequest))
}
if !saveToField.CanSet() {
panic(fmt.Sprintf("Unable to set the value of field named %q on the context", contextFieldNameForRequest))
}
newObject := reflect.New(fieldType)
err := json.NewDecoder(r.Body).Decode(newObject.Elem().Addr().Interface())
if err != nil {
if err == io.EOF {
return ErrRequestBodyIncomplete
}
return err
}
saveToField.Set(newObject)
return nil
}
func Request(field interface{}, errorHandlerCustom func(web.ResponseWriter, error)) func(
interface{}, web.ResponseWriter, *web.Request, web.NextMiddlewareFunc) {
errorHandler := ErrorHandler
if errorHandlerCustom != nil {
errorHandler = errorHandlerCustom
}
fieldType := reflect.TypeOf(field)
return func(ctx interface{}, rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
err := decodeBodyToJSON(ctx, fieldType, r)
if err != nil {
errorHandler(rw, err)
return
}
next(rw, r)
}
}
func ErrorHandler(rw web.ResponseWriter, err error) {
if rw.Written() {
panic(fmt.Sprintf("Data already started to be sent to the client and i had an error: %s", err))
}
rw.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err)
}