binding.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package binding
  5. import (
  6. "encoding/json"
  7. "encoding/xml"
  8. "errors"
  9. "net/http"
  10. "reflect"
  11. "strconv"
  12. "strings"
  13. )
  14. type (
  15. Binding interface {
  16. Bind(*http.Request, interface{}) error
  17. }
  18. // JSON binding
  19. jsonBinding struct{}
  20. // XML binding
  21. xmlBinding struct{}
  22. // form binding
  23. formBinding struct{}
  24. // multipart form binding
  25. multipartFormBinding struct{}
  26. )
  27. const MAX_MEMORY = 1 * 1024 * 1024
  28. var (
  29. JSON = jsonBinding{}
  30. XML = xmlBinding{}
  31. Form = formBinding{} // todo
  32. MultipartForm = multipartFormBinding{}
  33. )
  34. func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {
  35. decoder := json.NewDecoder(req.Body)
  36. if err := decoder.Decode(obj); err == nil {
  37. return Validate(obj)
  38. } else {
  39. return err
  40. }
  41. }
  42. func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {
  43. decoder := xml.NewDecoder(req.Body)
  44. if err := decoder.Decode(obj); err == nil {
  45. return Validate(obj)
  46. } else {
  47. return err
  48. }
  49. }
  50. func (_ formBinding) Bind(req *http.Request, obj interface{}) error {
  51. if err := req.ParseForm(); err != nil {
  52. return err
  53. }
  54. if err := mapForm(obj, req.Form); err != nil {
  55. return err
  56. }
  57. return Validate(obj)
  58. }
  59. func (_ multipartFormBinding) Bind(req *http.Request, obj interface{}) error {
  60. if err := req.ParseMultipartForm(MAX_MEMORY); err != nil {
  61. return err
  62. }
  63. if err := mapForm(obj, req.Form); err != nil {
  64. return err
  65. }
  66. return Validate(obj)
  67. }
  68. func mapForm(ptr interface{}, form map[string][]string) error {
  69. typ := reflect.TypeOf(ptr).Elem()
  70. formStruct := reflect.ValueOf(ptr).Elem()
  71. for i := 0; i < typ.NumField(); i++ {
  72. typeField := typ.Field(i)
  73. if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
  74. structField := formStruct.Field(i)
  75. if !structField.CanSet() {
  76. continue
  77. }
  78. inputValue, exists := form[inputFieldName]
  79. if !exists {
  80. continue
  81. }
  82. numElems := len(inputValue)
  83. if structField.Kind() == reflect.Slice && numElems > 0 {
  84. sliceOf := structField.Type().Elem().Kind()
  85. slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
  86. for i := 0; i < numElems; i++ {
  87. if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil {
  88. return err
  89. }
  90. }
  91. formStruct.Field(i).Set(slice)
  92. } else {
  93. if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {
  94. return err
  95. }
  96. }
  97. }
  98. }
  99. return nil
  100. }
  101. func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {
  102. switch valueKind {
  103. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  104. if val == "" {
  105. val = "0"
  106. }
  107. intVal, err := strconv.Atoi(val)
  108. if err != nil {
  109. return err
  110. } else {
  111. structField.SetInt(int64(intVal))
  112. }
  113. case reflect.Bool:
  114. if val == "" {
  115. val = "false"
  116. }
  117. boolVal, err := strconv.ParseBool(val)
  118. if err != nil {
  119. return err
  120. } else {
  121. structField.SetBool(boolVal)
  122. }
  123. case reflect.Float32:
  124. if val == "" {
  125. val = "0.0"
  126. }
  127. floatVal, err := strconv.ParseFloat(val, 32)
  128. if err != nil {
  129. return err
  130. } else {
  131. structField.SetFloat(floatVal)
  132. }
  133. case reflect.Float64:
  134. if val == "" {
  135. val = "0.0"
  136. }
  137. floatVal, err := strconv.ParseFloat(val, 64)
  138. if err != nil {
  139. return err
  140. } else {
  141. structField.SetFloat(floatVal)
  142. }
  143. case reflect.String:
  144. structField.SetString(val)
  145. }
  146. return nil
  147. }
  148. // Don't pass in pointers to bind to. Can lead to bugs. See:
  149. // https://github.com/codegangsta/martini-contrib/issues/40
  150. // https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
  151. func ensureNotPointer(obj interface{}) {
  152. if reflect.TypeOf(obj).Kind() == reflect.Ptr {
  153. panic("Pointers are not accepted as binding models")
  154. }
  155. }
  156. func Validate(obj interface{}, parents ...string) error {
  157. typ := reflect.TypeOf(obj)
  158. val := reflect.ValueOf(obj)
  159. if typ.Kind() == reflect.Ptr {
  160. typ = typ.Elem()
  161. val = val.Elem()
  162. }
  163. switch typ.Kind() {
  164. case reflect.Struct:
  165. for i := 0; i < typ.NumField(); i++ {
  166. field := typ.Field(i)
  167. // Allow ignored and unexported fields in the struct
  168. if len(field.PkgPath) > 0 || field.Tag.Get("form") == "-" {
  169. continue
  170. }
  171. fieldValue := val.Field(i).Interface()
  172. zero := reflect.Zero(field.Type).Interface()
  173. if strings.Index(field.Tag.Get("binding"), "required") > -1 {
  174. fieldType := field.Type.Kind()
  175. if fieldType == reflect.Struct {
  176. if reflect.DeepEqual(zero, fieldValue) {
  177. return errors.New("Required " + field.Name)
  178. }
  179. err := Validate(fieldValue, field.Name)
  180. if err != nil {
  181. return err
  182. }
  183. } else if reflect.DeepEqual(zero, fieldValue) {
  184. if len(parents) > 0 {
  185. return errors.New("Required " + field.Name + " on " + parents[0])
  186. } else {
  187. return errors.New("Required " + field.Name)
  188. }
  189. } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {
  190. err := Validate(fieldValue)
  191. if err != nil {
  192. return err
  193. }
  194. }
  195. } else {
  196. fieldType := field.Type.Kind()
  197. if fieldType == reflect.Struct {
  198. if reflect.DeepEqual(zero, fieldValue) {
  199. continue
  200. }
  201. err := Validate(fieldValue, field.Name)
  202. if err != nil {
  203. return err
  204. }
  205. } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {
  206. err := Validate(fieldValue, field.Name)
  207. if err != nil {
  208. return err
  209. }
  210. }
  211. }
  212. }
  213. case reflect.Slice:
  214. for i := 0; i < val.Len(); i++ {
  215. fieldValue := val.Index(i).Interface()
  216. err := Validate(fieldValue)
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. default:
  222. return nil
  223. }
  224. return nil
  225. }