-
Notifications
You must be signed in to change notification settings - Fork 4
/
formjson.go
107 lines (100 loc) · 2.48 KB
/
formjson.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package formjson
import (
"encoding/json"
"net/http"
"net/url"
"strconv"
"strings"
"golang.org/x/net/context"
"github.com/rs/xhandler"
)
// Handler detects when a POST/PUT/PATCH content type is JSON, and transparently convert
// the JSON content into a standard PostForm. This does only support posting of a JSON dictionary
// containing string => string key value pairs.
func Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleFormJSONRequest(r)
h.ServeHTTP(w, r)
})
}
// HandlerC detects when a POST/PUT/PATCH content type is JSON, and transparently convert
// the JSON content into a standard PostForm. This does only support posting of a JSON dictionary
// containing string => string key value pairs.
func HandlerC(h xhandler.HandlerC) xhandler.HandlerC {
return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
handleFormJSONRequest(r)
h.ServeHTTPC(ctx, w, r)
})
}
func handleFormJSONRequest(r *http.Request) {
if strings.Index(r.Header.Get("Content-Type"), "application/json") == -1 {
return
}
switch r.Method {
case "POST":
case "PUT":
case "PATCH":
// whitelisted methods
default:
return
}
// Try to decode body using a restrictive type
decoder := json.NewDecoder(r.Body)
var d map[string]interface{}
if err := decoder.Decode(&d); err != nil {
return
}
// Inject parsed data into PostForm
r.PostForm = url.Values{}
for k, v := range d {
switch t := v.(type) {
case string:
r.PostForm.Set(k, t)
case float64:
r.PostForm.Set(k, strconv.FormatFloat(t, 'f', -1, 64))
case bool:
if t {
r.PostForm.Set(k, "1")
} else {
r.PostForm.Set(k, "0")
}
case []interface{}:
r.PostForm[k] = []string{}
for _, sv := range t {
switch st := sv.(type) {
case string:
r.PostForm.Add(k, st)
case float64:
r.PostForm.Add(k, strconv.FormatFloat(st, 'f', -1, 64))
case bool:
if st {
r.PostForm.Add(k, "1")
} else {
r.PostForm.Add(k, "0")
}
default:
// Do not translate array partially
r.PostForm.Del(k)
break
}
}
}
}
// Build the Form property
if len(r.PostForm) > 0 {
r.Form = url.Values{}
for k, vs := range r.PostForm {
r.Form[k] = []string{}
for _, v := range vs {
r.Form.Add(k, v)
}
}
if r.URL != nil {
if newValues, err := url.ParseQuery(r.URL.RawQuery); err == nil {
for k, v := range newValues {
r.Form.Set(k, v[0])
}
}
}
}
}