form_mapping.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. "errors"
  8. "fmt"
  9. "reflect"
  10. "strconv"
  11. "strings"
  12. "time"
  13. //"github.com/gin-gonic/gin/internal/json"
  14. )
  15. var errUnknownType = errors.New("Unknown type")
  16. func mapUri(ptr interface{}, m map[string][]string) error {
  17. return mapFormByTag(ptr, m, "uri")
  18. }
  19. func mapForm(ptr interface{}, form map[string][]string) error {
  20. return mapFormByTag(ptr, form, "form")
  21. }
  22. var emptyField = reflect.StructField{}
  23. func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error {
  24. return mappingByPtr(ptr, formSource(form), tag)
  25. }
  26. // setter tries to set value on a walking by fields of a struct
  27. type setter interface {
  28. TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSetted bool, err error)
  29. }
  30. type formSource map[string][]string
  31. var _ setter = formSource(nil)
  32. // TrySet tries to set a value by request's form source (like map[string][]string)
  33. func (form formSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) {
  34. return setByForm(value, field, form, tagValue, opt)
  35. }
  36. func mappingByPtr(ptr interface{}, setter setter, tag string) error {
  37. _, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag)
  38. return err
  39. }
  40. func mapping(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {
  41. var vKind = value.Kind()
  42. if vKind == reflect.Ptr {
  43. var isNew bool
  44. vPtr := value
  45. if value.IsNil() {
  46. isNew = true
  47. vPtr = reflect.New(value.Type().Elem())
  48. }
  49. isSetted, err := mapping(vPtr.Elem(), field, setter, tag)
  50. if err != nil {
  51. return false, err
  52. }
  53. if isNew && isSetted {
  54. value.Set(vPtr)
  55. }
  56. return isSetted, nil
  57. }
  58. ok, err := tryToSetValue(value, field, setter, tag)
  59. if err != nil {
  60. return false, err
  61. }
  62. if ok {
  63. return true, nil
  64. }
  65. if vKind == reflect.Struct {
  66. tValue := value.Type()
  67. var isSetted bool
  68. for i := 0; i < value.NumField(); i++ {
  69. if !value.Field(i).CanSet() {
  70. continue
  71. }
  72. ok, err := mapping(value.Field(i), tValue.Field(i), setter, tag)
  73. if err != nil {
  74. return false, err
  75. }
  76. isSetted = isSetted || ok
  77. }
  78. return isSetted, nil
  79. }
  80. return false, nil
  81. }
  82. type setOptions struct {
  83. isDefaultExists bool
  84. defaultValue string
  85. }
  86. func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {
  87. var tagValue string
  88. var setOpt setOptions
  89. tagValue = field.Tag.Get(tag)
  90. tagValue, opts := head(tagValue, ",")
  91. if tagValue == "-" { // just ignoring this field
  92. return false, nil
  93. }
  94. if tagValue == "" { // default value is FieldName
  95. tagValue = field.Name
  96. }
  97. if tagValue == "" { // when field is "emptyField" variable
  98. return false, nil
  99. }
  100. var opt string
  101. for len(opts) > 0 {
  102. opt, opts = head(opts, ",")
  103. k, v := head(opt, "=")
  104. switch k {
  105. case "default":
  106. setOpt.isDefaultExists = true
  107. setOpt.defaultValue = v
  108. }
  109. }
  110. return setter.TrySet(value, field, tagValue, setOpt)
  111. }
  112. func setByForm(value reflect.Value, field reflect.StructField, form map[string][]string, tagValue string, opt setOptions) (isSetted bool, err error) {
  113. vs, ok := form[tagValue]
  114. if !ok && !opt.isDefaultExists {
  115. return false, nil
  116. }
  117. switch value.Kind() {
  118. case reflect.Slice:
  119. if !ok {
  120. vs = []string{opt.defaultValue}
  121. }
  122. return true, setSlice(vs, value, field)
  123. case reflect.Array:
  124. if !ok {
  125. vs = []string{opt.defaultValue}
  126. }
  127. if len(vs) != value.Len() {
  128. return false, fmt.Errorf("%q is not valid value for %s", vs, value.Type().String())
  129. }
  130. return true, setArray(vs, value, field)
  131. default:
  132. var val string
  133. if !ok {
  134. val = opt.defaultValue
  135. }
  136. if len(vs) > 0 {
  137. val = vs[0]
  138. }
  139. return true, setWithProperType(val, value, field)
  140. }
  141. }
  142. func setWithProperType(val string, value reflect.Value, field reflect.StructField) error {
  143. switch value.Kind() {
  144. case reflect.Int:
  145. return setIntField(val, 0, value)
  146. case reflect.Int8:
  147. return setIntField(val, 8, value)
  148. case reflect.Int16:
  149. return setIntField(val, 16, value)
  150. case reflect.Int32:
  151. return setIntField(val, 32, value)
  152. case reflect.Int64:
  153. switch value.Interface().(type) {
  154. case time.Duration:
  155. return setTimeDuration(val, value, field)
  156. }
  157. return setIntField(val, 64, value)
  158. case reflect.Uint:
  159. return setUintField(val, 0, value)
  160. case reflect.Uint8:
  161. return setUintField(val, 8, value)
  162. case reflect.Uint16:
  163. return setUintField(val, 16, value)
  164. case reflect.Uint32:
  165. return setUintField(val, 32, value)
  166. case reflect.Uint64:
  167. return setUintField(val, 64, value)
  168. case reflect.Bool:
  169. return setBoolField(val, value)
  170. case reflect.Float32:
  171. return setFloatField(val, 32, value)
  172. case reflect.Float64:
  173. return setFloatField(val, 64, value)
  174. case reflect.String:
  175. value.SetString(val)
  176. case reflect.Struct:
  177. switch value.Interface().(type) {
  178. case time.Time:
  179. return setTimeField(val, field, value)
  180. }
  181. return json.Unmarshal([]byte(val), value.Addr().Interface())
  182. case reflect.Map:
  183. return json.Unmarshal([]byte(val), value.Addr().Interface())
  184. default:
  185. return errUnknownType
  186. }
  187. return nil
  188. }
  189. func setIntField(val string, bitSize int, field reflect.Value) error {
  190. if val == "" {
  191. val = "0"
  192. }
  193. intVal, err := strconv.ParseInt(val, 10, bitSize)
  194. if err == nil {
  195. field.SetInt(intVal)
  196. }
  197. return err
  198. }
  199. func setUintField(val string, bitSize int, field reflect.Value) error {
  200. if val == "" {
  201. val = "0"
  202. }
  203. uintVal, err := strconv.ParseUint(val, 10, bitSize)
  204. if err == nil {
  205. field.SetUint(uintVal)
  206. }
  207. return err
  208. }
  209. func setBoolField(val string, field reflect.Value) error {
  210. if val == "" {
  211. val = "false"
  212. }
  213. boolVal, err := strconv.ParseBool(val)
  214. if err == nil {
  215. field.SetBool(boolVal)
  216. }
  217. return err
  218. }
  219. func setFloatField(val string, bitSize int, field reflect.Value) error {
  220. if val == "" {
  221. val = "0.0"
  222. }
  223. floatVal, err := strconv.ParseFloat(val, bitSize)
  224. if err == nil {
  225. field.SetFloat(floatVal)
  226. }
  227. return err
  228. }
  229. func setTimeField(val string, structField reflect.StructField, value reflect.Value) error {
  230. timeFormat := structField.Tag.Get("time_format")
  231. if timeFormat == "" {
  232. timeFormat = time.RFC3339
  233. }
  234. if val == "" {
  235. value.Set(reflect.ValueOf(time.Time{}))
  236. return nil
  237. }
  238. l := time.Local
  239. if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC {
  240. l = time.UTC
  241. }
  242. if locTag := structField.Tag.Get("time_location"); locTag != "" {
  243. loc, err := time.LoadLocation(locTag)
  244. if err != nil {
  245. return err
  246. }
  247. l = loc
  248. }
  249. t, err := time.ParseInLocation(timeFormat, val, l)
  250. if err != nil {
  251. return err
  252. }
  253. value.Set(reflect.ValueOf(t))
  254. return nil
  255. }
  256. func setArray(vals []string, value reflect.Value, field reflect.StructField) error {
  257. for i, s := range vals {
  258. err := setWithProperType(s, value.Index(i), field)
  259. if err != nil {
  260. return err
  261. }
  262. }
  263. return nil
  264. }
  265. func setSlice(vals []string, value reflect.Value, field reflect.StructField) error {
  266. slice := reflect.MakeSlice(value.Type(), len(vals), len(vals))
  267. err := setArray(vals, slice, field)
  268. if err != nil {
  269. return err
  270. }
  271. value.Set(slice)
  272. return nil
  273. }
  274. func setTimeDuration(val string, value reflect.Value, field reflect.StructField) error {
  275. d, err := time.ParseDuration(val)
  276. if err != nil {
  277. return err
  278. }
  279. value.Set(reflect.ValueOf(d))
  280. return nil
  281. }
  282. func head(str, sep string) (head string, tail string) {
  283. idx := strings.Index(str, sep)
  284. if idx < 0 {
  285. return str, ""
  286. }
  287. return str[:idx], str[idx+len(sep):]
  288. }