binding.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. )
  25. var (
  26. JSON = jsonBinding{}
  27. XML = xmlBinding{}
  28. Form = formBinding{} // todo
  29. )
  30. func (_ jsonBinding) Bind(req *http.Request, obj interface{}) error {
  31. decoder := json.NewDecoder(req.Body)
  32. if err := decoder.Decode(obj); err == nil {
  33. return Validate(obj)
  34. } else {
  35. return err
  36. }
  37. }
  38. func (_ xmlBinding) Bind(req *http.Request, obj interface{}) error {
  39. decoder := xml.NewDecoder(req.Body)
  40. if err := decoder.Decode(obj); err == nil {
  41. return Validate(obj)
  42. } else {
  43. return err
  44. }
  45. }
  46. func (_ formBinding) Bind(req *http.Request, obj interface{}) error {
  47. if err := req.ParseForm(); err != nil {
  48. return err
  49. }
  50. if err := mapForm(obj, req.Form); err != nil {
  51. return err
  52. }
  53. return Validate(obj)
  54. }
  55. func mapForm(ptr interface{}, form map[string][]string) error {
  56. typ := reflect.TypeOf(ptr).Elem()
  57. formStruct := reflect.ValueOf(ptr).Elem()
  58. for i := 0; i < typ.NumField(); i++ {
  59. typeField := typ.Field(i)
  60. if inputFieldName := typeField.Tag.Get("form"); inputFieldName != "" {
  61. structField := formStruct.Field(i)
  62. if !structField.CanSet() {
  63. continue
  64. }
  65. inputValue, exists := form[inputFieldName]
  66. if !exists {
  67. continue
  68. }
  69. numElems := len(inputValue)
  70. if structField.Kind() == reflect.Slice && numElems > 0 {
  71. sliceOf := structField.Type().Elem().Kind()
  72. slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
  73. for i := 0; i < numElems; i++ {
  74. if err := setWithProperType(sliceOf, inputValue[i], slice.Index(i)); err != nil {
  75. return err
  76. }
  77. }
  78. formStruct.Field(i).Set(slice)
  79. } else {
  80. if err := setWithProperType(typeField.Type.Kind(), inputValue[0], structField); err != nil {
  81. return err
  82. }
  83. }
  84. }
  85. }
  86. return nil
  87. }
  88. func setWithProperType(valueKind reflect.Kind, val string, structField reflect.Value) error {
  89. switch valueKind {
  90. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  91. if val == "" {
  92. val = "0"
  93. }
  94. intVal, err := strconv.Atoi(val)
  95. if err != nil {
  96. return err
  97. } else {
  98. structField.SetInt(int64(intVal))
  99. }
  100. case reflect.Bool:
  101. if val == "" {
  102. val = "false"
  103. }
  104. boolVal, err := strconv.ParseBool(val)
  105. if err != nil {
  106. return err
  107. } else {
  108. structField.SetBool(boolVal)
  109. }
  110. case reflect.Float32:
  111. if val == "" {
  112. val = "0.0"
  113. }
  114. floatVal, err := strconv.ParseFloat(val, 32)
  115. if err != nil {
  116. return err
  117. } else {
  118. structField.SetFloat(floatVal)
  119. }
  120. case reflect.Float64:
  121. if val == "" {
  122. val = "0.0"
  123. }
  124. floatVal, err := strconv.ParseFloat(val, 64)
  125. if err != nil {
  126. return err
  127. } else {
  128. structField.SetFloat(floatVal)
  129. }
  130. case reflect.String:
  131. structField.SetString(val)
  132. }
  133. return nil
  134. }
  135. // Don't pass in pointers to bind to. Can lead to bugs. See:
  136. // https://github.com/codegangsta/martini-contrib/issues/40
  137. // https://github.com/codegangsta/martini-contrib/pull/34#issuecomment-29683659
  138. func ensureNotPointer(obj interface{}) {
  139. if reflect.TypeOf(obj).Kind() == reflect.Ptr {
  140. panic("Pointers are not accepted as binding models")
  141. }
  142. }
  143. func Validate(obj interface{}) error {
  144. typ := reflect.TypeOf(obj)
  145. val := reflect.ValueOf(obj)
  146. if typ.Kind() == reflect.Ptr {
  147. typ = typ.Elem()
  148. val = val.Elem()
  149. }
  150. switch typ.Kind() {
  151. case reflect.Struct:
  152. for i := 0; i < typ.NumField(); i++ {
  153. field := typ.Field(i)
  154. // Allow ignored and unexported fields in the struct
  155. if field.Tag.Get("form") == "-" || field.PkgPath != "" {
  156. continue
  157. }
  158. fieldValue := val.Field(i).Interface()
  159. zero := reflect.Zero(field.Type).Interface()
  160. if strings.Index(field.Tag.Get("binding"), "required") > -1 {
  161. fieldType := field.Type.Kind()
  162. if fieldType == reflect.Struct {
  163. err := Validate(fieldValue)
  164. if err != nil {
  165. return err
  166. }
  167. } else if reflect.DeepEqual(zero, fieldValue) {
  168. return errors.New("Required " + field.Name)
  169. } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {
  170. err := Validate(fieldValue)
  171. if err != nil {
  172. return err
  173. }
  174. }
  175. }
  176. }
  177. case reflect.Slice:
  178. for i := 0; i < val.Len(); i++ {
  179. fieldValue := val.Index(i).Interface()
  180. err := Validate(fieldValue)
  181. if err != nil {
  182. return err
  183. }
  184. }
  185. default:
  186. return nil
  187. }
  188. return nil
  189. }