You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
961 B

3 years ago
  1. package utils
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. //@author: [piexlmax](https://github.com/piexlmax)
  8. //@function: StructToMap
  9. //@description: 利用反射将结构体转化为map
  10. //@param: obj interface{}
  11. //@return: map[string]interface{}
  12. func StructToMap(obj interface{}) map[string]interface{} {
  13. obj1 := reflect.TypeOf(obj)
  14. obj2 := reflect.ValueOf(obj)
  15. data := make(map[string]interface{})
  16. for i := 0; i < obj1.NumField(); i++ {
  17. if obj1.Field(i).Tag.Get("mapstructure") != "" {
  18. data[obj1.Field(i).Tag.Get("mapstructure")] = obj2.Field(i).Interface()
  19. } else {
  20. data[obj1.Field(i).Name] = obj2.Field(i).Interface()
  21. }
  22. }
  23. return data
  24. }
  25. //@author: [piexlmax](https://github.com/piexlmax)
  26. //@function: ArrayToString
  27. //@description: 将数组格式化为字符串
  28. //@param: array []interface{}
  29. //@return: string
  30. func ArrayToString(array []interface{}) string {
  31. return strings.Replace(strings.Trim(fmt.Sprint(array), "[]"), " ", ",", -1)
  32. }