gconv_structs.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gconv
  7. import (
  8. "reflect"
  9. "github.com/gogf/gf/v2/errors/gcode"
  10. "github.com/gogf/gf/v2/errors/gerror"
  11. "github.com/gogf/gf/v2/internal/json"
  12. )
  13. // Structs converts any slice to given struct slice.
  14. // Also see Scan, Struct.
  15. func Structs(params interface{}, pointer interface{}, mapping ...map[string]string) (err error) {
  16. return Scan(params, pointer, mapping...)
  17. }
  18. // StructsTag acts as Structs but also with support for priority tag feature, which retrieves the
  19. // specified tags for `params` key-value items to struct attribute names mapping.
  20. // The parameter `priorityTag` supports multiple tags that can be joined with char ','.
  21. func StructsTag(params interface{}, pointer interface{}, priorityTag string) (err error) {
  22. return doStructs(params, pointer, nil, priorityTag)
  23. }
  24. // doStructs converts any slice to given struct slice.
  25. //
  26. // It automatically checks and converts json string to []map if `params` is string/[]byte.
  27. //
  28. // The parameter `pointer` should be type of pointer to slice of struct.
  29. // Note that if `pointer` is a pointer to another pointer of type of slice of struct,
  30. // it will create the struct/pointer internally.
  31. func doStructs(params interface{}, pointer interface{}, mapping map[string]string, priorityTag string) (err error) {
  32. if params == nil {
  33. // If `params` is nil, no conversion.
  34. return nil
  35. }
  36. if pointer == nil {
  37. return gerror.NewCode(gcode.CodeInvalidParameter, "object pointer cannot be nil")
  38. }
  39. if doStructsByDirectReflectSet(params, pointer) {
  40. return nil
  41. }
  42. defer func() {
  43. // Catch the panic, especially the reflection operation panics.
  44. if exception := recover(); exception != nil {
  45. if v, ok := exception.(error); ok && gerror.HasStack(v) {
  46. err = v
  47. } else {
  48. err = gerror.NewCodeSkipf(gcode.CodeInternalError, 1, "%+v", exception)
  49. }
  50. }
  51. }()
  52. // If given `params` is JSON, it then uses json.Unmarshal doing the converting.
  53. switch r := params.(type) {
  54. case []byte:
  55. if json.Valid(r) {
  56. if rv, ok := pointer.(reflect.Value); ok {
  57. if rv.Kind() == reflect.Ptr {
  58. return json.UnmarshalUseNumber(r, rv.Interface())
  59. }
  60. } else {
  61. return json.UnmarshalUseNumber(r, pointer)
  62. }
  63. }
  64. case string:
  65. if paramsBytes := []byte(r); json.Valid(paramsBytes) {
  66. if rv, ok := pointer.(reflect.Value); ok {
  67. if rv.Kind() == reflect.Ptr {
  68. return json.UnmarshalUseNumber(paramsBytes, rv.Interface())
  69. }
  70. } else {
  71. return json.UnmarshalUseNumber(paramsBytes, pointer)
  72. }
  73. }
  74. }
  75. // Pointer type check.
  76. pointerRv, ok := pointer.(reflect.Value)
  77. if !ok {
  78. pointerRv = reflect.ValueOf(pointer)
  79. if kind := pointerRv.Kind(); kind != reflect.Ptr {
  80. return gerror.NewCodef(gcode.CodeInvalidParameter, "pointer should be type of pointer, but got: %v", kind)
  81. }
  82. }
  83. // Converting `params` to map slice.
  84. var (
  85. paramsList []interface{}
  86. paramsRv = reflect.ValueOf(params)
  87. paramsKind = paramsRv.Kind()
  88. )
  89. for paramsKind == reflect.Ptr {
  90. paramsRv = paramsRv.Elem()
  91. paramsKind = paramsRv.Kind()
  92. }
  93. switch paramsKind {
  94. case reflect.Slice, reflect.Array:
  95. paramsList = make([]interface{}, paramsRv.Len())
  96. for i := 0; i < paramsRv.Len(); i++ {
  97. paramsList[i] = paramsRv.Index(i).Interface()
  98. }
  99. default:
  100. var paramsMaps = Maps(params)
  101. paramsList = make([]interface{}, len(paramsMaps))
  102. for i := 0; i < len(paramsMaps); i++ {
  103. paramsList[i] = paramsMaps[i]
  104. }
  105. }
  106. // If `params` is an empty slice, no conversion.
  107. if len(paramsList) == 0 {
  108. return nil
  109. }
  110. var (
  111. reflectElemArray = reflect.MakeSlice(pointerRv.Type().Elem(), len(paramsList), len(paramsList))
  112. itemType = reflectElemArray.Index(0).Type()
  113. itemTypeKind = itemType.Kind()
  114. pointerRvElem = pointerRv.Elem()
  115. pointerRvLength = pointerRvElem.Len()
  116. )
  117. if itemTypeKind == reflect.Ptr {
  118. // Pointer element.
  119. for i := 0; i < len(paramsList); i++ {
  120. var tempReflectValue reflect.Value
  121. if i < pointerRvLength {
  122. // Might be nil.
  123. tempReflectValue = pointerRvElem.Index(i).Elem()
  124. }
  125. if !tempReflectValue.IsValid() {
  126. tempReflectValue = reflect.New(itemType.Elem()).Elem()
  127. }
  128. if err = doStruct(paramsList[i], tempReflectValue, mapping, priorityTag); err != nil {
  129. return err
  130. }
  131. reflectElemArray.Index(i).Set(tempReflectValue.Addr())
  132. }
  133. } else {
  134. // Struct element.
  135. for i := 0; i < len(paramsList); i++ {
  136. var tempReflectValue reflect.Value
  137. if i < pointerRvLength {
  138. tempReflectValue = pointerRvElem.Index(i)
  139. } else {
  140. tempReflectValue = reflect.New(itemType).Elem()
  141. }
  142. if err = doStruct(paramsList[i], tempReflectValue, mapping, priorityTag); err != nil {
  143. return err
  144. }
  145. reflectElemArray.Index(i).Set(tempReflectValue)
  146. }
  147. }
  148. pointerRv.Elem().Set(reflectElemArray)
  149. return nil
  150. }
  151. // doStructsByDirectReflectSet do the converting directly using reflect Set.
  152. // It returns true if success, or else false.
  153. func doStructsByDirectReflectSet(params interface{}, pointer interface{}) (ok bool) {
  154. v1 := reflect.ValueOf(pointer)
  155. v2 := reflect.ValueOf(params)
  156. if v1.Kind() == reflect.Ptr {
  157. if elem := v1.Elem(); elem.IsValid() && elem.Type() == v2.Type() {
  158. elem.Set(v2)
  159. ok = true
  160. }
  161. }
  162. return ok
  163. }