main.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package utils
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "reflect"
  7. "github.com/guonaihong/gout"
  8. )
  9. func JsonEncode(v interface{}) string {
  10. jsonStr, _ := json.Marshal(v)
  11. return string(jsonStr)
  12. }
  13. // MD5加密
  14. func Md5(src string) string {
  15. m := md5.New()
  16. m.Write([]byte(src))
  17. res := hex.EncodeToString(m.Sum(nil))
  18. return res
  19. }
  20. func StructToGoutH(item interface{}) gout.H {
  21. result := make(gout.H)
  22. itemValue := reflect.ValueOf(item)
  23. // 如果传入的是指针,则获取其所指向的元素
  24. if itemValue.Kind() == reflect.Ptr {
  25. itemValue = itemValue.Elem()
  26. }
  27. // 确保传入的是结构体
  28. if itemValue.Kind() != reflect.Struct {
  29. return result
  30. }
  31. itemType := itemValue.Type()
  32. for i := 0; i < itemValue.NumField(); i++ {
  33. // 获取字段名和值
  34. field := itemType.Field(i)
  35. fieldValue := itemValue.Field(i).Interface()
  36. // 获取json标签,如果存在则使用json标签作为字段名
  37. jsonTag := field.Tag.Get("json")
  38. if jsonTag != "" && jsonTag != "-" {
  39. result[jsonTag] = fieldValue
  40. } else {
  41. result[field.Name] = fieldValue
  42. }
  43. }
  44. return result
  45. }