forked from extrame/goblet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfill.go
284 lines (255 loc) · 7.39 KB
/
fill.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package goblet
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io/ioutil"
"mime/multipart"
"net/url"
"reflect"
"strings"
"github.com/extrame/unmarshall"
"github.com/sirupsen/logrus"
)
type FormFillFn func(content string) (interface{}, error)
type MultiFormFillFn func(ctx *Context, id string) (interface{}, error)
func (s *Server) AddFillForTypeInForm(typ string, fn FormFillFn) {
s.filler[typ] = fn
}
func (s *Server) AddFillForTypeInMultiForm(typ string, fn MultiFormFillFn) {
s.multiFiller[typ] = fn
}
// types that impliment RequestDecoder can unmarshal
// the request body into an apropriate type/struct
type RequestDecoder interface {
Unmarshal(cx *Context, v interface{}, autofill bool) error
}
// a JSON decoder for request body (just a wrapper to json.Unmarshal)
type JsonRequestDecoder struct{}
func (d *JsonRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) (err error) {
// read body
if cx.fill_bts == nil {
cx.fill_bts, err = ioutil.ReadAll(cx.request.Body)
}
if err != nil {
return err
}
return json.Unmarshal(cx.fill_bts, v)
}
// an XML decoder for request body
type XmlRequestDecoder struct{}
func (d *XmlRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) (err error) {
// read body
if cx.fill_bts == nil {
cx.fill_bts, err = ioutil.ReadAll(cx.request.Body)
}
if err != nil {
return err
}
if err = xml.Unmarshal(cx.fill_bts, v); err != nil {
logrus.Errorf("[Fill Error]Request:%s,Err:%s\n", string(cx.fill_bts), err.Error())
}
return err
}
// a form-enc decoder for request body
type FormRequestDecoder struct{}
type FileGetter func(string) (multipart.File, *multipart.FileHeader, error)
func (d *FormRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) error {
if cx.request.Form == nil {
cx.request.ParseForm()
}
var maxlength = 0
for k, _ := range cx.request.Form {
if len(k) > maxlength {
maxlength = len(k)
}
}
var unmarshaller = unmarshall.Unmarshaller{
Values: func() map[string][]string {
return cx.request.Form
},
ValuesGetter: func(prefix string) url.Values {
values := (*map[string][]string)(&cx.request.Form)
var sub = make(url.Values)
if values != nil {
for k, v := range *values {
if strings.HasPrefix(k, prefix+"[") {
sub[k] = v
}
}
}
return sub
},
ValueGetter: func(tag string) []string {
values := (*map[string][]string)(&cx.request.Form)
if values != nil {
var lower = strings.ToLower(tag)
if results, ok := (*values)[tag]; ok {
return results
}
if results, ok := (*values)[lower]; ok {
return results
}
if results, ok := (*values)[tag+"[]"]; ok {
return results
}
if results, ok := (*values)[lower+"[]"]; ok {
return results
}
}
return []string{}
},
Tag: "goblet",
DefaultTag: "default",
MaxLength: maxlength,
TagConcatter: concatPrefix,
BaseName: func(path string, prefix string) string {
return strings.Split(strings.TrimPrefix(path, prefix+"["), "]")[0]
},
AutoFill: autofill,
}
for typ, fn := range cx.Server.filler {
if unmarshaller.FillForSpecifiledType == nil {
unmarshaller.FillForSpecifiledType = make(map[string]func(id string) (reflect.Value, error))
}
unmarshaller.FillForSpecifiledType[typ] = func(content string) (reflect.Value, error) {
obj, err := fn(content)
return reflect.ValueOf(obj), err
}
}
return unmarshaller.Unmarshall(v)
}
// a form-enc decoder for request body
type MultiFormRequestDecoder struct{}
func (d *MultiFormRequestDecoder) Unmarshal(cx *Context, v interface{}, autofill bool) error {
err := cx.request.ParseMultipartForm(32 << 20)
if err != nil {
return err
}
values := (map[string][]string)(cx.request.Form)
if cx.request.MultipartForm == nil {
return errors.New("MultipartForm is empty")
}
var maxlength = 0
for k, v := range cx.request.MultipartForm.Value {
values[k] = v
if len(k) > maxlength {
maxlength = len(k)
}
}
for k, _ := range cx.request.MultipartForm.File {
if len(k) > maxlength {
maxlength = len(k)
}
}
var unmarshaller = unmarshall.Unmarshaller{
Values: func() map[string][]string {
return values
},
MaxLength: maxlength,
ValueGetter: func(tag string) []string {
return values[tag]
},
ValuesGetter: func(prefix string) url.Values {
var sub = make(url.Values)
if values != nil {
for k, v := range values {
if strings.HasPrefix(k, prefix+"[") {
sub[k] = v
}
}
}
return sub
},
TagConcatter: concatPrefix,
BaseName: func(path string, prefix string) string {
return strings.Split(strings.TrimPrefix(path, prefix+"["), "]")[0]
},
FillForSpecifiledType: map[string]func(id string) (reflect.Value, error){
"github.com/bjxujiang/goblet.File": func(id string) (reflect.Value, error) {
var file File
var err error
var f multipart.File
var h *multipart.FileHeader
if f, h, err = cx.request.FormFile(id); err == nil {
file.Name = h.Filename
file.Header = h.Header
file.rc = f
return reflect.ValueOf(file), err
} else {
return reflect.ValueOf(nil), err
}
},
},
AutoFill: autofill,
Tag: "goblet",
DefaultTag: "default",
}
for typ, fn := range cx.Server.multiFiller {
unmarshaller.FillForSpecifiledType[typ] = func(id string) (reflect.Value, error) {
obj, err := fn(cx, id)
return reflect.ValueOf(obj), err
}
}
return unmarshaller.Unmarshall(v)
}
// map of Content-Type -> RequestDecoders
var decoders map[string]RequestDecoder = map[string]RequestDecoder{
"application/json": new(JsonRequestDecoder),
"application/xml": new(XmlRequestDecoder),
"text/xml": new(XmlRequestDecoder),
"application/x-www-form-urlencoded": new(FormRequestDecoder),
"text/plain": new(FormRequestDecoder),
"multipart/form-data": new(MultiFormRequestDecoder),
}
// goweb.Context Helper function to fill a variable with the contents
// of the request body. The body will be decoded based
// on the content-type and an apropriate RequestDecoder
// automatically selected
// If you want to use md5 function for the specified field, please add
// md5 tag for it. AND the md5 tag must be the last one of the tags, so
// if you have no other tag, please add ',' before md5
func (cx *Context) Fill(v interface{}, fills ...bool) error {
// get content type
ct := cx.request.Header.Get("Content-Type")
//if method is GET, only form in url is supported
if cx.request.Method == "GET" {
ct = "application/x-www-form-urlencoded"
}
// default to urlencoded
if ct == "" {
if cx.Server.Basic.DefaultType != "" {
ct = cx.Server.Basic.DefaultType
} else {
ct = "application/x-www-form-urlencoded"
}
} else if strings.HasPrefix(ct, "text/plain") && cx.Server.Basic.DefaultType != "" {
ct = cx.Server.Basic.DefaultType
}
autofill := true
if len(fills) > 0 {
autofill = fills[0]
}
return cx.FillAs(v, autofill, ct)
}
func (cx *Context) FillAs(v interface{}, autofill bool, ct string) error {
// ignore charset (after ';')
ct = strings.Split(ct, ";")[0]
// get request decoder
decoder, ok := decoders[ct]
if ok != true {
return fmt.Errorf("Cannot decode request for %s data", ct)
}
// decode
err := decoder.Unmarshal(cx, v, autofill)
if err != nil {
fmt.Println(err)
return err
}
// all clear
return nil
}
func concatPrefix(prefix, tag string) string {
return prefix + "[" + tag + "]"
}