binding.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. // Copyright 2013 The Martini Contrib Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package binding
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "reflect"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. "unicode/utf8"
  16. "github.com/go-martini/martini"
  17. )
  18. /*
  19. To the land of Middle-ware Earth:
  20. One func to rule them all,
  21. One func to find them,
  22. One func to bring them all,
  23. And in this package BIND them.
  24. */
  25. // Bind accepts a copy of an empty struct and populates it with
  26. // values from the request (if deserialization is successful). It
  27. // wraps up the functionality of the Form and Json middleware
  28. // according to the Content-Type of the request, and it guesses
  29. // if no Content-Type is specified. Bind invokes the ErrorHandler
  30. // middleware to bail out if errors occurred. If you want to perform
  31. // your own error handling, use Form or Json middleware directly.
  32. // An interface pointer can be added as a second argument in order
  33. // to map the struct to a specific interface.
  34. func Bind(obj interface{}, ifacePtr ...interface{}) martini.Handler {
  35. return func(context martini.Context, req *http.Request) {
  36. contentType := req.Header.Get("Content-Type")
  37. if strings.Contains(contentType, "form-urlencoded") {
  38. context.Invoke(Form(obj, ifacePtr...))
  39. } else if strings.Contains(contentType, "multipart/form-data") {
  40. context.Invoke(MultipartForm(obj, ifacePtr...))
  41. } else if strings.Contains(contentType, "json") {
  42. context.Invoke(Json(obj, ifacePtr...))
  43. } else {
  44. context.Invoke(Json(obj, ifacePtr...))
  45. if getErrors(context).Count() > 0 {
  46. context.Invoke(Form(obj, ifacePtr...))
  47. }
  48. }
  49. context.Invoke(ErrorHandler)
  50. }
  51. }
  52. // BindIgnErr will do the exactly same thing as Bind but without any
  53. // error handling, which user has freedom to deal with them.
  54. // This allows user take advantages of validation.
  55. func BindIgnErr(obj interface{}, ifacePtr ...interface{}) martini.Handler {
  56. return func(context martini.Context, req *http.Request) {
  57. contentType := req.Header.Get("Content-Type")
  58. if strings.Contains(contentType, "form-urlencoded") {
  59. context.Invoke(Form(obj, ifacePtr...))
  60. } else if strings.Contains(contentType, "multipart/form-data") {
  61. context.Invoke(MultipartForm(obj, ifacePtr...))
  62. } else if strings.Contains(contentType, "json") {
  63. context.Invoke(Json(obj, ifacePtr...))
  64. } else {
  65. context.Invoke(Json(obj, ifacePtr...))
  66. if getErrors(context).Count() > 0 {
  67. context.Invoke(Form(obj, ifacePtr...))
  68. }
  69. }
  70. }
  71. }
  72. // Form is middleware to deserialize form-urlencoded data from the request.
  73. // It gets data from the form-urlencoded body, if present, or from the
  74. // query string. It uses the http.Request.ParseForm() method
  75. // to perform deserialization, then reflection is used to map each field
  76. // into the struct with the proper type. Structs with primitive slice types
  77. // (bool, float, int, string) can support deserialization of repeated form
  78. // keys, for example: key=val1&key=val2&key=val3
  79. // An interface pointer can be added as a second argument in order
  80. // to map the struct to a specific interface.
  81. func Form(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
  82. return func(context martini.Context, req *http.Request) {
  83. ensureNotPointer(formStruct)
  84. formStruct := reflect.New(reflect.TypeOf(formStruct))
  85. errors := newErrors()
  86. parseErr := req.ParseForm()
  87. // Format validation of the request body or the URL would add considerable overhead,
  88. // and ParseForm does not complain when URL encoding is off.
  89. // Because an empty request body or url can also mean absence of all needed values,
  90. // it is not in all cases a bad request, so let's return 422.
  91. if parseErr != nil {
  92. errors.Overall[BindingDeserializationError] = parseErr.Error()
  93. }
  94. mapForm(formStruct, req.Form, errors)
  95. validateAndMap(formStruct, context, errors, ifacePtr...)
  96. }
  97. }
  98. func MultipartForm(formStruct interface{}, ifacePtr ...interface{}) martini.Handler {
  99. return func(context martini.Context, req *http.Request) {
  100. ensureNotPointer(formStruct)
  101. formStruct := reflect.New(reflect.TypeOf(formStruct))
  102. errors := newErrors()
  103. // Workaround for multipart forms returning nil instead of an error
  104. // when content is not multipart
  105. // https://code.google.com/p/go/issues/detail?id=6334
  106. multipartReader, err := req.MultipartReader()
  107. if err != nil {
  108. errors.Overall[BindingDeserializationError] = err.Error()
  109. } else {
  110. form, parseErr := multipartReader.ReadForm(MaxMemory)
  111. if parseErr != nil {
  112. errors.Overall[BindingDeserializationError] = parseErr.Error()
  113. }
  114. req.MultipartForm = form
  115. }
  116. mapForm(formStruct, req.MultipartForm.Value, errors)
  117. validateAndMap(formStruct, context, errors, ifacePtr...)
  118. }
  119. }
  120. // Json is middleware to deserialize a JSON payload from the request
  121. // into the struct that is passed in. The resulting struct is then
  122. // validated, but no error handling is actually performed here.
  123. // An interface pointer can be added as a second argument in order
  124. // to map the struct to a specific interface.
  125. func Json(jsonStruct interface{}, ifacePtr ...interface{}) martini.Handler {
  126. return func(context martini.Context, req *http.Request) {
  127. ensureNotPointer(jsonStruct)
  128. jsonStruct := reflect.New(reflect.TypeOf(jsonStruct))
  129. errors := newErrors()
  130. if req.Body != nil {
  131. defer req.Body.Close()
  132. }
  133. if err := json.NewDecoder(req.Body).Decode(jsonStruct.Interface()); err != nil && err != io.EOF {
  134. errors.Overall[BindingDeserializationError] = err.Error()
  135. }
  136. validateAndMap(jsonStruct, context, errors, ifacePtr...)
  137. }
  138. }
  139. // Validate is middleware to enforce required fields. If the struct
  140. // passed in is a Validator, then the user-defined Validate method
  141. // is executed, and its errors are mapped to the context. This middleware
  142. // performs no error handling: it merely detects them and maps them.
  143. func Validate(obj interface{}) martini.Handler {
  144. return func(context martini.Context, req *http.Request) {
  145. errors := newErrors()
  146. validateStruct(errors, obj)
  147. if validator, ok := obj.(Validator); ok {
  148. validator.Validate(errors, req, context)
  149. }
  150. context.Map(*errors)
  151. }
  152. }
  153. var (
  154. alphaDashPattern = regexp.MustCompile("[^\\d\\w-_]")
  155. alphaDashDotPattern = regexp.MustCompile("[^\\d\\w-_\\.]")
  156. emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")
  157. urlPattern = regexp.MustCompile(`(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?`)
  158. )
  159. func validateStruct(errors *BindingErrors, obj interface{}) {
  160. typ := reflect.TypeOf(obj)
  161. val := reflect.ValueOf(obj)
  162. if typ.Kind() == reflect.Ptr {
  163. typ = typ.Elem()
  164. val = val.Elem()
  165. }
  166. for i := 0; i < typ.NumField(); i++ {
  167. field := typ.Field(i)
  168. // Allow ignored fields in the struct
  169. if field.Tag.Get("form") == "-" {
  170. continue
  171. }
  172. fieldValue := val.Field(i).Interface()
  173. if field.Type.Kind() == reflect.Struct {
  174. validateStruct(errors, fieldValue)
  175. continue
  176. }
  177. zero := reflect.Zero(field.Type).Interface()
  178. // Match rules.
  179. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  180. if len(rule) == 0 {
  181. continue
  182. }
  183. switch {
  184. case rule == "Required":
  185. if reflect.DeepEqual(zero, fieldValue) {
  186. errors.Fields[field.Name] = BindingRequireError
  187. break
  188. }
  189. case rule == "AlphaDash":
  190. if alphaDashPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  191. errors.Fields[field.Name] = BindingAlphaDashError
  192. break
  193. }
  194. case rule == "AlphaDashDot":
  195. if alphaDashDotPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  196. errors.Fields[field.Name] = BindingAlphaDashDotError
  197. break
  198. }
  199. case strings.HasPrefix(rule, "MinSize("):
  200. min, err := strconv.Atoi(rule[8 : len(rule)-1])
  201. if err != nil {
  202. errors.Overall["MinSize"] = err.Error()
  203. break
  204. }
  205. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) < min {
  206. errors.Fields[field.Name] = BindingMinSizeError
  207. break
  208. }
  209. v := reflect.ValueOf(fieldValue)
  210. if v.Kind() == reflect.Slice && v.Len() < min {
  211. errors.Fields[field.Name] = BindingMinSizeError
  212. break
  213. }
  214. case strings.HasPrefix(rule, "MaxSize("):
  215. max, err := strconv.Atoi(rule[8 : len(rule)-1])
  216. if err != nil {
  217. errors.Overall["MaxSize"] = err.Error()
  218. break
  219. }
  220. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) > max {
  221. errors.Fields[field.Name] = BindingMaxSizeError
  222. break
  223. }
  224. v := reflect.ValueOf(fieldValue)
  225. if v.Kind() == reflect.Slice && v.Len() > max {
  226. errors.Fields[field.Name] = BindingMinSizeError
  227. break
  228. }
  229. case rule == "Email":
  230. if !emailPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  231. errors.Fields[field.Name] = BindingEmailError
  232. break
  233. }
  234. case rule == "Url":
  235. if !urlPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  236. errors.Fields[field.Name] = BindingUrlError
  237. break
  238. }
  239. }
  240. }
  241. }
  242. }
  243. func mapForm(formStruct reflect.Value, form map[string][]string, errors *BindingErrors) {
  244. typ := formStruct.Elem().Type()
  245. for i := 0; i < typ.NumField(); i++ {
  246. typeField := typ.Field(i)
  247. if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
  248. structField := formStruct.Elem().Field(i)
  249. if !structField.CanSet() {
  250. continue
  251. }
  252. inputValue, exists := form[inputFieldName]
  253. if !exists {
  254. continue
  255. }
  256. numElems := len(inputValue)
  257. if structField.Kind() == reflect.Slice && numElems > 0 {
  258. sliceOf := structField.Type().Elem().Kind()
  259. slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
  260. for i := 0; i < numElems; i++ {
  261. setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
  262. }
  263. formStruct.Elem().Field(i).Set(slice)
  264. } else {
  265. setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
  266. }
  267. }
  268. }
  269. }
  270. // ErrorHandler simply counts the number of errors in the
  271. // context and, if more than 0, writes a 400 Bad Request
  272. // response and a JSON payload describing the errors with
  273. // the "Content-Type" set to "application/json".
  274. // Middleware remaining on the stack will not even see the request
  275. // if, by this point, there are any errors.
  276. // This is a "default" handler, of sorts, and you are
  277. // welcome to use your own instead. The Bind middleware
  278. // invokes this automatically for convenience.
  279. func ErrorHandler(errs BindingErrors, resp http.ResponseWriter) {
  280. if errs.Count() > 0 {
  281. resp.Header().Set("Content-Type", "application/json; charset=utf-8")
  282. if _, ok := errs.Overall[BindingDeserializationError]; ok {
  283. resp.WriteHeader(http.StatusBadRequest)
  284. } else {
  285. resp.WriteHeader(422)
  286. }
  287. errOutput, _ := json.Marshal(errs)
  288. resp.Write(errOutput)
  289. return
  290. }
  291. }
  292. // This sets the value in a struct of an indeterminate type to the
  293. // matching value from the request (via Form middleware) in the
  294. // same type, so that not all deserialized values have to be strings.
  295. // Supported types are string, int, float, and bool.
  296. func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors *BindingErrors) {
  297. switch valueKind {
  298. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  299. if val == "" {
  300. val = "0"
  301. }
  302. intVal, err := strconv.ParseInt(val, 10, 64)
  303. if err != nil {
  304. errors.Fields[nameInTag] = BindingIntegerTypeError
  305. } else {
  306. structField.SetInt(intVal)
  307. }
  308. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  309. if val == "" {
  310. val = "0"
  311. }
  312. uintVal, err := strconv.ParseUint(val, 10, 64)
  313. if err != nil {
  314. errors.Fields[nameInTag] = BindingIntegerTypeError
  315. } else {
  316. structField.SetUint(uintVal)
  317. }
  318. case reflect.Bool:
  319. structField.SetBool(val == "on")
  320. case reflect.Float32:
  321. if val == "" {
  322. val = "0.0"
  323. }
  324. floatVal, err := strconv.ParseFloat(val, 32)
  325. if err != nil {
  326. errors.Fields[nameInTag] = BindingFloatTypeError
  327. } else {
  328. structField.SetFloat(floatVal)
  329. }
  330. case reflect.Float64:
  331. if val == "" {
  332. val = "0.0"
  333. }
  334. floatVal, err := strconv.ParseFloat(val, 64)
  335. if err != nil {
  336. errors.Fields[nameInTag] = BindingFloatTypeError
  337. } else {
  338. structField.SetFloat(floatVal)
  339. }
  340. case reflect.String:
  341. structField.SetString(val)
  342. }
  343. }
  344. // Don't pass in pointers to bind to. Can lead to bugs. See:
  345. // https://github.com/codegangsta/martini-contrib/issues/40
  346. // https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
  347. func ensureNotPointer(obj interface{}) {
  348. if reflect.TypeOf(obj).Kind() == reflect.Ptr {
  349. panic("Pointers are not accepted as binding models")
  350. }
  351. }
  352. // Performs validation and combines errors from validation
  353. // with errors from deserialization, then maps both the
  354. // resulting struct and the errors to the context.
  355. func validateAndMap(obj reflect.Value, context martini.Context, errors *BindingErrors, ifacePtr ...interface{}) {
  356. context.Invoke(Validate(obj.Interface()))
  357. errors.Combine(getErrors(context))
  358. context.Map(*errors)
  359. context.Map(obj.Elem().Interface())
  360. if len(ifacePtr) > 0 {
  361. context.MapTo(obj.Elem().Interface(), ifacePtr[0])
  362. }
  363. }
  364. func newErrors() *BindingErrors {
  365. return &BindingErrors{make(map[string]string), make(map[string]string)}
  366. }
  367. func getErrors(context martini.Context) BindingErrors {
  368. return context.Get(reflect.TypeOf(BindingErrors{})).Interface().(BindingErrors)
  369. }
  370. type (
  371. // Implement the Validator interface to define your own input
  372. // validation before the request even gets to your application.
  373. // The Validate method will be executed during the validation phase.
  374. Validator interface {
  375. Validate(*BindingErrors, *http.Request, martini.Context)
  376. }
  377. )
  378. var (
  379. // Maximum amount of memory to use when parsing a multipart form.
  380. // Set this to whatever value you prefer; default is 10 MB.
  381. MaxMemory = int64(1024 * 1024 * 10)
  382. )
  383. // Errors represents the contract of the response body when the
  384. // binding step fails before getting to the application.
  385. type BindingErrors struct {
  386. Overall map[string]string `json:"overall"`
  387. Fields map[string]string `json:"fields"`
  388. }
  389. // Total errors is the sum of errors with the request overall
  390. // and errors on individual fields.
  391. func (err BindingErrors) Count() int {
  392. return len(err.Overall) + len(err.Fields)
  393. }
  394. func (this *BindingErrors) Combine(other BindingErrors) {
  395. for key, val := range other.Fields {
  396. if _, exists := this.Fields[key]; !exists {
  397. this.Fields[key] = val
  398. }
  399. }
  400. for key, val := range other.Overall {
  401. if _, exists := this.Overall[key]; !exists {
  402. this.Overall[key] = val
  403. }
  404. }
  405. }
  406. const (
  407. BindingRequireError string = "Required"
  408. BindingAlphaDashError string = "AlphaDash"
  409. BindingAlphaDashDotError string = "AlphaDashDot"
  410. BindingMinSizeError string = "MinSize"
  411. BindingMaxSizeError string = "MaxSize"
  412. BindingEmailError string = "Email"
  413. BindingUrlError string = "Url"
  414. BindingDeserializationError string = "DeserializationError"
  415. BindingIntegerTypeError string = "IntegerTypeError"
  416. BindingBooleanTypeError string = "BooleanTypeError"
  417. BindingFloatTypeError string = "FloatTypeError"
  418. )