binding.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. // Copyright 2014 Martini Authors
  2. // Copyright 2014 The Macaron Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. // Package binding is a middleware that provides request data binding and validation for Macaron.
  16. package binding
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "mime/multipart"
  22. "net/http"
  23. "reflect"
  24. "regexp"
  25. "strconv"
  26. "strings"
  27. "unicode/utf8"
  28. "github.com/Unknwon/com"
  29. "gopkg.in/macaron.v1"
  30. )
  31. const _VERSION = "0.3.2"
  32. func Version() string {
  33. return _VERSION
  34. }
  35. func bind(ctx *macaron.Context, obj interface{}, ifacePtr ...interface{}) {
  36. contentType := ctx.Req.Header.Get("Content-Type")
  37. if ctx.Req.Method == "POST" || ctx.Req.Method == "PUT" || len(contentType) > 0 {
  38. switch {
  39. case strings.Contains(contentType, "form-urlencoded"):
  40. ctx.Invoke(Form(obj, ifacePtr...))
  41. case strings.Contains(contentType, "multipart/form-data"):
  42. ctx.Invoke(MultipartForm(obj, ifacePtr...))
  43. case strings.Contains(contentType, "json"):
  44. ctx.Invoke(Json(obj, ifacePtr...))
  45. default:
  46. var errors Errors
  47. if contentType == "" {
  48. errors.Add([]string{}, ERR_CONTENT_TYPE, "Empty Content-Type")
  49. } else {
  50. errors.Add([]string{}, ERR_CONTENT_TYPE, "Unsupported Content-Type")
  51. }
  52. ctx.Map(errors)
  53. ctx.Map(obj) // Map a fake struct so handler won't panic.
  54. }
  55. } else {
  56. ctx.Invoke(Form(obj, ifacePtr...))
  57. }
  58. }
  59. const (
  60. _JSON_CONTENT_TYPE = "application/json; charset=utf-8"
  61. STATUS_UNPROCESSABLE_ENTITY = 422
  62. )
  63. // errorHandler simply counts the number of errors in the
  64. // context and, if more than 0, writes a response with an
  65. // error code and a JSON payload describing the errors.
  66. // The response will have a JSON content-type.
  67. // Middleware remaining on the stack will not even see the request
  68. // if, by this point, there are any errors.
  69. // This is a "default" handler, of sorts, and you are
  70. // welcome to use your own instead. The Bind middleware
  71. // invokes this automatically for convenience.
  72. func errorHandler(errs Errors, rw http.ResponseWriter) {
  73. if len(errs) > 0 {
  74. rw.Header().Set("Content-Type", _JSON_CONTENT_TYPE)
  75. if errs.Has(ERR_DESERIALIZATION) {
  76. rw.WriteHeader(http.StatusBadRequest)
  77. } else if errs.Has(ERR_CONTENT_TYPE) {
  78. rw.WriteHeader(http.StatusUnsupportedMediaType)
  79. } else {
  80. rw.WriteHeader(STATUS_UNPROCESSABLE_ENTITY)
  81. }
  82. errOutput, _ := json.Marshal(errs)
  83. rw.Write(errOutput)
  84. return
  85. }
  86. }
  87. // Bind wraps up the functionality of the Form and Json middleware
  88. // according to the Content-Type and verb of the request.
  89. // A Content-Type is required for POST and PUT requests.
  90. // Bind invokes the ErrorHandler middleware to bail out if errors
  91. // occurred. If you want to perform your own error handling, use
  92. // Form or Json middleware directly. An interface pointer can
  93. // be added as a second argument in order to map the struct to
  94. // a specific interface.
  95. func Bind(obj interface{}, ifacePtr ...interface{}) macaron.Handler {
  96. return func(ctx *macaron.Context) {
  97. bind(ctx, obj, ifacePtr...)
  98. if handler, ok := obj.(ErrorHandler); ok {
  99. ctx.Invoke(handler.Error)
  100. } else {
  101. ctx.Invoke(errorHandler)
  102. }
  103. }
  104. }
  105. // BindIgnErr will do the exactly same thing as Bind but without any
  106. // error handling, which user has freedom to deal with them.
  107. // This allows user take advantages of validation.
  108. func BindIgnErr(obj interface{}, ifacePtr ...interface{}) macaron.Handler {
  109. return func(ctx *macaron.Context) {
  110. bind(ctx, obj, ifacePtr...)
  111. }
  112. }
  113. // Form is middleware to deserialize form-urlencoded data from the request.
  114. // It gets data from the form-urlencoded body, if present, or from the
  115. // query string. It uses the http.Request.ParseForm() method
  116. // to perform deserialization, then reflection is used to map each field
  117. // into the struct with the proper type. Structs with primitive slice types
  118. // (bool, float, int, string) can support deserialization of repeated form
  119. // keys, for example: key=val1&key=val2&key=val3
  120. // An interface pointer can be added as a second argument in order
  121. // to map the struct to a specific interface.
  122. func Form(formStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
  123. return func(ctx *macaron.Context) {
  124. var errors Errors
  125. ensureNotPointer(formStruct)
  126. formStruct := reflect.New(reflect.TypeOf(formStruct))
  127. parseErr := ctx.Req.ParseForm()
  128. // Format validation of the request body or the URL would add considerable overhead,
  129. // and ParseForm does not complain when URL encoding is off.
  130. // Because an empty request body or url can also mean absence of all needed values,
  131. // it is not in all cases a bad request, so let's return 422.
  132. if parseErr != nil {
  133. errors.Add([]string{}, ERR_DESERIALIZATION, parseErr.Error())
  134. }
  135. mapForm(formStruct, ctx.Req.Form, nil, errors)
  136. validateAndMap(formStruct, ctx, errors, ifacePtr...)
  137. }
  138. }
  139. // Maximum amount of memory to use when parsing a multipart form.
  140. // Set this to whatever value you prefer; default is 10 MB.
  141. var MaxMemory = int64(1024 * 1024 * 10)
  142. // MultipartForm works much like Form, except it can parse multipart forms
  143. // and handle file uploads. Like the other deserialization middleware handlers,
  144. // you can pass in an interface to make the interface available for injection
  145. // into other handlers later.
  146. func MultipartForm(formStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
  147. return func(ctx *macaron.Context) {
  148. var errors Errors
  149. ensureNotPointer(formStruct)
  150. formStruct := reflect.New(reflect.TypeOf(formStruct))
  151. // This if check is necessary due to https://github.com/martini-contrib/csrf/issues/6
  152. if ctx.Req.MultipartForm == nil {
  153. // Workaround for multipart forms returning nil instead of an error
  154. // when content is not multipart; see https://code.google.com/p/go/issues/detail?id=6334
  155. if multipartReader, err := ctx.Req.MultipartReader(); err != nil {
  156. errors.Add([]string{}, ERR_DESERIALIZATION, err.Error())
  157. } else {
  158. form, parseErr := multipartReader.ReadForm(MaxMemory)
  159. if parseErr != nil {
  160. errors.Add([]string{}, ERR_DESERIALIZATION, parseErr.Error())
  161. }
  162. if ctx.Req.Form == nil {
  163. ctx.Req.ParseForm()
  164. }
  165. for k, v := range form.Value {
  166. ctx.Req.Form[k] = append(ctx.Req.Form[k], v...)
  167. }
  168. ctx.Req.MultipartForm = form
  169. }
  170. }
  171. mapForm(formStruct, ctx.Req.MultipartForm.Value, ctx.Req.MultipartForm.File, errors)
  172. validateAndMap(formStruct, ctx, errors, ifacePtr...)
  173. }
  174. }
  175. // Json is middleware to deserialize a JSON payload from the request
  176. // into the struct that is passed in. The resulting struct is then
  177. // validated, but no error handling is actually performed here.
  178. // An interface pointer can be added as a second argument in order
  179. // to map the struct to a specific interface.
  180. func Json(jsonStruct interface{}, ifacePtr ...interface{}) macaron.Handler {
  181. return func(ctx *macaron.Context) {
  182. var errors Errors
  183. ensureNotPointer(jsonStruct)
  184. jsonStruct := reflect.New(reflect.TypeOf(jsonStruct))
  185. if ctx.Req.Request.Body != nil {
  186. defer ctx.Req.Request.Body.Close()
  187. err := json.NewDecoder(ctx.Req.Request.Body).Decode(jsonStruct.Interface())
  188. if err != nil && err != io.EOF {
  189. errors.Add([]string{}, ERR_DESERIALIZATION, err.Error())
  190. }
  191. }
  192. validateAndMap(jsonStruct, ctx, errors, ifacePtr...)
  193. }
  194. }
  195. // Validate is middleware to enforce required fields. If the struct
  196. // passed in implements Validator, then the user-defined Validate method
  197. // is executed, and its errors are mapped to the context. This middleware
  198. // performs no error handling: it merely detects errors and maps them.
  199. func Validate(obj interface{}) macaron.Handler {
  200. return func(ctx *macaron.Context) {
  201. var errors Errors
  202. v := reflect.ValueOf(obj)
  203. k := v.Kind()
  204. if k == reflect.Interface || k == reflect.Ptr {
  205. v = v.Elem()
  206. k = v.Kind()
  207. }
  208. if k == reflect.Slice || k == reflect.Array {
  209. for i := 0; i < v.Len(); i++ {
  210. e := v.Index(i).Interface()
  211. errors = validateStruct(errors, e)
  212. if validator, ok := e.(Validator); ok {
  213. errors = validator.Validate(ctx, errors)
  214. }
  215. }
  216. } else {
  217. errors = validateStruct(errors, obj)
  218. if validator, ok := obj.(Validator); ok {
  219. errors = validator.Validate(ctx, errors)
  220. }
  221. }
  222. ctx.Map(errors)
  223. }
  224. }
  225. var (
  226. AlphaDashPattern = regexp.MustCompile("[^\\d\\w-_]")
  227. AlphaDashDotPattern = regexp.MustCompile("[^\\d\\w-_\\.]")
  228. EmailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")
  229. URLPattern = regexp.MustCompile(`(http|https):\/\/(?:\\S+(?::\\S*)?@)?[\w\-_]+(\.[\w\-_]+)*([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?`)
  230. )
  231. type (
  232. // Rule represents a validation rule.
  233. Rule struct {
  234. // IsMatch checks if rule matches.
  235. IsMatch func(string) bool
  236. // IsValid applies validation rule to condition.
  237. IsValid func(Errors, string, interface{}) (bool, Errors)
  238. }
  239. // RuleMapper represents a validation rule mapper,
  240. // it allwos users to add custom validation rules.
  241. RuleMapper []*Rule
  242. )
  243. var ruleMapper RuleMapper
  244. // AddRule adds new validation rule.
  245. func AddRule(r *Rule) {
  246. ruleMapper = append(ruleMapper, r)
  247. }
  248. func in(fieldValue interface{}, arr string) bool {
  249. val := fmt.Sprintf("%v", fieldValue)
  250. vals := strings.Split(arr, ",")
  251. isIn := false
  252. for _, v := range vals {
  253. if v == val {
  254. isIn = true
  255. break
  256. }
  257. }
  258. return isIn
  259. }
  260. func parseFormName(raw, actual string) string {
  261. if len(actual) > 0 {
  262. return actual
  263. }
  264. return nameMapper(raw)
  265. }
  266. // Performs required field checking on a struct
  267. func validateStruct(errors Errors, obj interface{}) Errors {
  268. typ := reflect.TypeOf(obj)
  269. val := reflect.ValueOf(obj)
  270. if typ.Kind() == reflect.Ptr {
  271. typ = typ.Elem()
  272. val = val.Elem()
  273. }
  274. for i := 0; i < typ.NumField(); i++ {
  275. field := typ.Field(i)
  276. // Allow ignored fields in the struct
  277. if field.Tag.Get("form") == "-" || !val.Field(i).CanInterface() {
  278. continue
  279. }
  280. fieldVal := val.Field(i)
  281. fieldValue := fieldVal.Interface()
  282. zero := reflect.Zero(field.Type).Interface()
  283. // Validate nested and embedded structs (if pointer, only do so if not nil)
  284. if field.Type.Kind() == reflect.Struct ||
  285. (field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue) &&
  286. field.Type.Elem().Kind() == reflect.Struct) {
  287. errors = validateStruct(errors, fieldValue)
  288. }
  289. errors = validateField(errors, zero, field, fieldVal, fieldValue)
  290. }
  291. return errors
  292. }
  293. func validateField(errors Errors, zero interface{}, field reflect.StructField, fieldVal reflect.Value, fieldValue interface{}) Errors {
  294. if fieldVal.Kind() == reflect.Slice {
  295. for i := 0; i < fieldVal.Len(); i++ {
  296. sliceVal := fieldVal.Index(i)
  297. if sliceVal.Kind() == reflect.Ptr {
  298. sliceVal = sliceVal.Elem()
  299. }
  300. sliceValue := sliceVal.Interface()
  301. zero := reflect.Zero(sliceVal.Type()).Interface()
  302. if sliceVal.Kind() == reflect.Struct ||
  303. (sliceVal.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, sliceValue) &&
  304. sliceVal.Elem().Kind() == reflect.Struct) {
  305. errors = validateStruct(errors, sliceValue)
  306. }
  307. /* Apply validation rules to each item in a slice. ISSUE #3
  308. else {
  309. errors = validateField(errors, zero, field, sliceVal, sliceValue)
  310. }*/
  311. }
  312. }
  313. VALIDATE_RULES:
  314. for _, rule := range strings.Split(field.Tag.Get("binding"), ";") {
  315. if len(rule) == 0 {
  316. continue
  317. }
  318. switch {
  319. case rule == "OmitEmpty":
  320. if reflect.DeepEqual(zero, fieldValue) {
  321. break VALIDATE_RULES
  322. }
  323. case rule == "Required":
  324. if reflect.DeepEqual(zero, fieldValue) {
  325. errors.Add([]string{field.Name}, ERR_REQUIRED, "Required")
  326. break VALIDATE_RULES
  327. }
  328. case rule == "AlphaDash":
  329. if AlphaDashPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  330. errors.Add([]string{field.Name}, ERR_ALPHA_DASH, "AlphaDash")
  331. break VALIDATE_RULES
  332. }
  333. case rule == "AlphaDashDot":
  334. if AlphaDashDotPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  335. errors.Add([]string{field.Name}, ERR_ALPHA_DASH_DOT, "AlphaDashDot")
  336. break VALIDATE_RULES
  337. }
  338. case strings.HasPrefix(rule, "Size("):
  339. size, _ := strconv.Atoi(rule[5 : len(rule)-1])
  340. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) != size {
  341. errors.Add([]string{field.Name}, ERR_SIZE, "Size")
  342. break VALIDATE_RULES
  343. }
  344. v := reflect.ValueOf(fieldValue)
  345. if v.Kind() == reflect.Slice && v.Len() != size {
  346. errors.Add([]string{field.Name}, ERR_SIZE, "Size")
  347. break VALIDATE_RULES
  348. }
  349. case strings.HasPrefix(rule, "MinSize("):
  350. min, _ := strconv.Atoi(rule[8 : len(rule)-1])
  351. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) < min {
  352. errors.Add([]string{field.Name}, ERR_MIN_SIZE, "MinSize")
  353. break VALIDATE_RULES
  354. }
  355. v := reflect.ValueOf(fieldValue)
  356. if v.Kind() == reflect.Slice && v.Len() < min {
  357. errors.Add([]string{field.Name}, ERR_MIN_SIZE, "MinSize")
  358. break VALIDATE_RULES
  359. }
  360. case strings.HasPrefix(rule, "MaxSize("):
  361. max, _ := strconv.Atoi(rule[8 : len(rule)-1])
  362. if str, ok := fieldValue.(string); ok && utf8.RuneCountInString(str) > max {
  363. errors.Add([]string{field.Name}, ERR_MAX_SIZE, "MaxSize")
  364. break VALIDATE_RULES
  365. }
  366. v := reflect.ValueOf(fieldValue)
  367. if v.Kind() == reflect.Slice && v.Len() > max {
  368. errors.Add([]string{field.Name}, ERR_MAX_SIZE, "MaxSize")
  369. break VALIDATE_RULES
  370. }
  371. case strings.HasPrefix(rule, "Range("):
  372. nums := strings.Split(rule[6:len(rule)-1], ",")
  373. if len(nums) != 2 {
  374. break VALIDATE_RULES
  375. }
  376. val := com.StrTo(fmt.Sprintf("%v", fieldValue)).MustInt()
  377. if val < com.StrTo(nums[0]).MustInt() || val > com.StrTo(nums[1]).MustInt() {
  378. errors.Add([]string{field.Name}, ERR_RANGE, "Range")
  379. break VALIDATE_RULES
  380. }
  381. case rule == "Email":
  382. if !EmailPattern.MatchString(fmt.Sprintf("%v", fieldValue)) {
  383. errors.Add([]string{field.Name}, ERR_EMAIL, "Email")
  384. break VALIDATE_RULES
  385. }
  386. case rule == "Url":
  387. str := fmt.Sprintf("%v", fieldValue)
  388. if len(str) == 0 {
  389. continue
  390. } else if !URLPattern.MatchString(str) {
  391. errors.Add([]string{field.Name}, ERR_URL, "Url")
  392. break VALIDATE_RULES
  393. }
  394. case strings.HasPrefix(rule, "In("):
  395. if !in(fieldValue, rule[3:len(rule)-1]) {
  396. errors.Add([]string{field.Name}, ERR_IN, "In")
  397. break VALIDATE_RULES
  398. }
  399. case strings.HasPrefix(rule, "NotIn("):
  400. if in(fieldValue, rule[6:len(rule)-1]) {
  401. errors.Add([]string{field.Name}, ERR_NOT_INT, "NotIn")
  402. break VALIDATE_RULES
  403. }
  404. case strings.HasPrefix(rule, "Include("):
  405. if !strings.Contains(fmt.Sprintf("%v", fieldValue), rule[8:len(rule)-1]) {
  406. errors.Add([]string{field.Name}, ERR_INCLUDE, "Include")
  407. break VALIDATE_RULES
  408. }
  409. case strings.HasPrefix(rule, "Exclude("):
  410. if strings.Contains(fmt.Sprintf("%v", fieldValue), rule[8:len(rule)-1]) {
  411. errors.Add([]string{field.Name}, ERR_EXCLUDE, "Exclude")
  412. break VALIDATE_RULES
  413. }
  414. case strings.HasPrefix(rule, "Default("):
  415. if reflect.DeepEqual(zero, fieldValue) {
  416. if fieldVal.CanAddr() {
  417. setWithProperType(field.Type.Kind(), rule[8:len(rule)-1], fieldVal, field.Tag.Get("form"), errors)
  418. } else {
  419. errors.Add([]string{field.Name}, ERR_EXCLUDE, "Default")
  420. break VALIDATE_RULES
  421. }
  422. }
  423. default:
  424. // Apply custom validation rules.
  425. var isValid bool
  426. for i := range ruleMapper {
  427. if ruleMapper[i].IsMatch(rule) {
  428. isValid, errors = ruleMapper[i].IsValid(errors, field.Name, fieldValue)
  429. if !isValid {
  430. break VALIDATE_RULES
  431. }
  432. }
  433. }
  434. }
  435. }
  436. return errors
  437. }
  438. // NameMapper represents a form tag name mapper.
  439. type NameMapper func(string) string
  440. var (
  441. nameMapper = func(field string) string {
  442. newstr := make([]rune, 0, len(field))
  443. for i, chr := range field {
  444. if isUpper := 'A' <= chr && chr <= 'Z'; isUpper {
  445. if i > 0 {
  446. newstr = append(newstr, '_')
  447. }
  448. chr -= ('A' - 'a')
  449. }
  450. newstr = append(newstr, chr)
  451. }
  452. return string(newstr)
  453. }
  454. )
  455. // SetNameMapper sets name mapper.
  456. func SetNameMapper(nm NameMapper) {
  457. nameMapper = nm
  458. }
  459. // Takes values from the form data and puts them into a struct
  460. func mapForm(formStruct reflect.Value, form map[string][]string,
  461. formfile map[string][]*multipart.FileHeader, errors Errors) {
  462. if formStruct.Kind() == reflect.Ptr {
  463. formStruct = formStruct.Elem()
  464. }
  465. typ := formStruct.Type()
  466. for i := 0; i < typ.NumField(); i++ {
  467. typeField := typ.Field(i)
  468. structField := formStruct.Field(i)
  469. if typeField.Type.Kind() == reflect.Ptr && typeField.Anonymous {
  470. structField.Set(reflect.New(typeField.Type.Elem()))
  471. mapForm(structField.Elem(), form, formfile, errors)
  472. if reflect.DeepEqual(structField.Elem().Interface(), reflect.Zero(structField.Elem().Type()).Interface()) {
  473. structField.Set(reflect.Zero(structField.Type()))
  474. }
  475. } else if typeField.Type.Kind() == reflect.Struct {
  476. mapForm(structField, form, formfile, errors)
  477. }
  478. inputFieldName := parseFormName(typeField.Name, typeField.Tag.Get("form"))
  479. if len(inputFieldName) == 0 || !structField.CanSet() {
  480. continue
  481. }
  482. inputValue, exists := form[inputFieldName]
  483. if exists {
  484. numElems := len(inputValue)
  485. if structField.Kind() == reflect.Slice && numElems > 0 {
  486. sliceOf := structField.Type().Elem().Kind()
  487. slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
  488. for i := 0; i < numElems; i++ {
  489. setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
  490. }
  491. formStruct.Field(i).Set(slice)
  492. } else {
  493. setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
  494. }
  495. continue
  496. }
  497. inputFile, exists := formfile[inputFieldName]
  498. if !exists {
  499. continue
  500. }
  501. fhType := reflect.TypeOf((*multipart.FileHeader)(nil))
  502. numElems := len(inputFile)
  503. if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType {
  504. slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
  505. for i := 0; i < numElems; i++ {
  506. slice.Index(i).Set(reflect.ValueOf(inputFile[i]))
  507. }
  508. structField.Set(slice)
  509. } else if structField.Type() == fhType {
  510. structField.Set(reflect.ValueOf(inputFile[0]))
  511. }
  512. }
  513. }
  514. // This sets the value in a struct of an indeterminate type to the
  515. // matching value from the request (via Form middleware) in the
  516. // same type, so that not all deserialized values have to be strings.
  517. // Supported types are string, int, float, and bool.
  518. func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value, nameInTag string, errors Errors) {
  519. switch valueKind {
  520. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  521. if val == "" {
  522. val = "0"
  523. }
  524. intVal, err := strconv.ParseInt(val, 10, 64)
  525. if err != nil {
  526. errors.Add([]string{nameInTag}, ERR_INTERGER_TYPE, "Value could not be parsed as integer")
  527. } else {
  528. structField.SetInt(intVal)
  529. }
  530. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  531. if val == "" {
  532. val = "0"
  533. }
  534. uintVal, err := strconv.ParseUint(val, 10, 64)
  535. if err != nil {
  536. errors.Add([]string{nameInTag}, ERR_INTERGER_TYPE, "Value could not be parsed as unsigned integer")
  537. } else {
  538. structField.SetUint(uintVal)
  539. }
  540. case reflect.Bool:
  541. if val == "on" {
  542. structField.SetBool(true)
  543. return
  544. }
  545. if val == "" {
  546. val = "false"
  547. }
  548. boolVal, err := strconv.ParseBool(val)
  549. if err != nil {
  550. errors.Add([]string{nameInTag}, ERR_BOOLEAN_TYPE, "Value could not be parsed as boolean")
  551. } else if boolVal {
  552. structField.SetBool(true)
  553. }
  554. case reflect.Float32:
  555. if val == "" {
  556. val = "0.0"
  557. }
  558. floatVal, err := strconv.ParseFloat(val, 32)
  559. if err != nil {
  560. errors.Add([]string{nameInTag}, ERR_FLOAT_TYPE, "Value could not be parsed as 32-bit float")
  561. } else {
  562. structField.SetFloat(floatVal)
  563. }
  564. case reflect.Float64:
  565. if val == "" {
  566. val = "0.0"
  567. }
  568. floatVal, err := strconv.ParseFloat(val, 64)
  569. if err != nil {
  570. errors.Add([]string{nameInTag}, ERR_FLOAT_TYPE, "Value could not be parsed as 64-bit float")
  571. } else {
  572. structField.SetFloat(floatVal)
  573. }
  574. case reflect.String:
  575. structField.SetString(val)
  576. }
  577. }
  578. // Don't pass in pointers to bind to. Can lead to bugs.
  579. func ensureNotPointer(obj interface{}) {
  580. if reflect.TypeOf(obj).Kind() == reflect.Ptr {
  581. panic("Pointers are not accepted as binding models")
  582. }
  583. }
  584. // Performs validation and combines errors from validation
  585. // with errors from deserialization, then maps both the
  586. // resulting struct and the errors to the context.
  587. func validateAndMap(obj reflect.Value, ctx *macaron.Context, errors Errors, ifacePtr ...interface{}) {
  588. ctx.Invoke(Validate(obj.Interface()))
  589. errors = append(errors, getErrors(ctx)...)
  590. ctx.Map(errors)
  591. ctx.Map(obj.Elem().Interface())
  592. if len(ifacePtr) > 0 {
  593. ctx.MapTo(obj.Elem().Interface(), ifacePtr[0])
  594. }
  595. }
  596. // getErrors simply gets the errors from the context (it's kind of a chore)
  597. func getErrors(ctx *macaron.Context) Errors {
  598. return ctx.GetVal(reflect.TypeOf(Errors{})).Interface().(Errors)
  599. }
  600. type (
  601. // ErrorHandler is the interface that has custom error handling process.
  602. ErrorHandler interface {
  603. // Error handles validation errors with custom process.
  604. Error(*macaron.Context, Errors)
  605. }
  606. // Validator is the interface that handles some rudimentary
  607. // request validation logic so your application doesn't have to.
  608. Validator interface {
  609. // Validate validates that the request is OK. It is recommended
  610. // that validation be limited to checking values for syntax and
  611. // semantics, enough to know that you can make sense of the request
  612. // in your application. For example, you might verify that a credit
  613. // card number matches a valid pattern, but you probably wouldn't
  614. // perform an actual credit card authorization here.
  615. Validate(*macaron.Context, Errors) Errors
  616. }
  617. )