form_mapping.go 8.7 KB

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