gconv_structs.go 5.5 KB

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