form_mapping.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. )
  14. var errUnknownType = errors.New("unknown type")
  15. func mapURI(ptr interface{}, m map[string][]string) error {
  16. return mapFormByTag(ptr, m, "uri")
  17. }
  18. func mapForm(ptr interface{}, form map[string][]string) error {
  19. return mapFormByTag(ptr, form, "form")
  20. }
  21. var emptyField = reflect.StructField{}
  22. func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error {
  23. return mappingByPtr(ptr, formSource(form), tag)
  24. }
  25. // setter tries to set value on a walking by fields of a struct
  26. type setter interface {
  27. TrySet(value reflect.Value, field reflect.StructField, key string, opt setOptions) (isSetted bool, err error)
  28. }
  29. type formSource map[string][]string
  30. var _ setter = formSource(nil)
  31. // TrySet tries to set a value by request's form source (like map[string][]string)
  32. func (form formSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) {
  33. return setByForm(value, field, form, tagValue, opt)
  34. }
  35. func mappingByPtr(ptr interface{}, setter setter, tag string) error {
  36. _, err := mapping(reflect.ValueOf(ptr), emptyField, setter, tag)
  37. return err
  38. }
  39. func mapping(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {
  40. if field.Tag.Get(tag) == "-" { // just ignoring this field
  41. return false, nil
  42. }
  43. var vKind = value.Kind()
  44. if vKind == reflect.Ptr {
  45. var isNew bool
  46. vPtr := value
  47. if value.IsNil() {
  48. isNew = true
  49. vPtr = reflect.New(value.Type().Elem())
  50. }
  51. isSetted, err := mapping(vPtr.Elem(), field, setter, tag)
  52. if err != nil {
  53. return false, err
  54. }
  55. if isNew && isSetted {
  56. value.Set(vPtr)
  57. }
  58. return isSetted, nil
  59. }
  60. if vKind != reflect.Struct || !field.Anonymous {
  61. ok, err := tryToSetValue(value, field, setter, tag)
  62. if err != nil {
  63. return false, err
  64. }
  65. if ok {
  66. return true, nil
  67. }
  68. }
  69. if vKind == reflect.Struct {
  70. tValue := value.Type()
  71. var isSetted bool
  72. for i := 0; i < value.NumField(); i++ {
  73. sf := tValue.Field(i)
  74. if sf.PkgPath != "" && !sf.Anonymous { // unexported
  75. continue
  76. }
  77. ok, err := mapping(value.Field(i), tValue.Field(i), setter, tag)
  78. if err != nil {
  79. return false, err
  80. }
  81. isSetted = isSetted || ok
  82. }
  83. return isSetted, nil
  84. }
  85. return false, nil
  86. }
  87. type setOptions struct {
  88. isDefaultExists bool
  89. defaultValue string
  90. }
  91. func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter, tag string) (bool, error) {
  92. var tagValue string
  93. var setOpt setOptions
  94. tagValue = field.Tag.Get(tag)
  95. tagValue, opts := head(tagValue, ",")
  96. if tagValue == "" { // default value is FieldName
  97. tagValue = field.Name
  98. }
  99. if tagValue == "" { // when field is "emptyField" variable
  100. return false, nil
  101. }
  102. var opt string
  103. for len(opts) > 0 {
  104. opt, opts = head(opts, ",")
  105. if k, v := head(opt, "="); k == "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(StringToBytes(val), value.Addr().Interface())
  182. case reflect.Map:
  183. return json.Unmarshal(StringToBytes(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. switch tf := strings.ToLower(timeFormat); tf {
  235. case "unix", "unixnano":
  236. tv, err := strconv.ParseInt(val, 10, 0)
  237. if err != nil {
  238. return err
  239. }
  240. d := time.Duration(1)
  241. if tf == "unixnano" {
  242. d = time.Second
  243. }
  244. t := time.Unix(tv/int64(d), tv%int64(d))
  245. value.Set(reflect.ValueOf(t))
  246. return nil
  247. }
  248. if val == "" {
  249. value.Set(reflect.ValueOf(time.Time{}))
  250. return nil
  251. }
  252. l := time.Local
  253. if isUTC, _ := strconv.ParseBool(structField.Tag.Get("time_utc")); isUTC {
  254. l = time.UTC
  255. }
  256. if locTag := structField.Tag.Get("time_location"); locTag != "" {
  257. loc, err := time.LoadLocation(locTag)
  258. if err != nil {
  259. return err
  260. }
  261. l = loc
  262. }
  263. t, err := time.ParseInLocation(timeFormat, val, l)
  264. if err != nil {
  265. return err
  266. }
  267. value.Set(reflect.ValueOf(t))
  268. return nil
  269. }
  270. func setArray(vals []string, value reflect.Value, field reflect.StructField) error {
  271. for i, s := range vals {
  272. err := setWithProperType(s, value.Index(i), field)
  273. if err != nil {
  274. return err
  275. }
  276. }
  277. return nil
  278. }
  279. func setSlice(vals []string, value reflect.Value, field reflect.StructField) error {
  280. slice := reflect.MakeSlice(value.Type(), len(vals), len(vals))
  281. err := setArray(vals, slice, field)
  282. if err != nil {
  283. return err
  284. }
  285. value.Set(slice)
  286. return nil
  287. }
  288. func setTimeDuration(val string, value reflect.Value, field reflect.StructField) error {
  289. d, err := time.ParseDuration(val)
  290. if err != nil {
  291. return err
  292. }
  293. value.Set(reflect.ValueOf(d))
  294. return nil
  295. }
  296. func head(str, sep string) (head string, tail string) {
  297. idx := strings.Index(str, sep)
  298. if idx < 0 {
  299. return str, ""
  300. }
  301. return str[:idx], str[idx+len(sep):]
  302. }