12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- package utils
- import (
- "crypto/md5"
- "encoding/hex"
- "encoding/json"
- "reflect"
- "github.com/guonaihong/gout"
- )
- func JsonEncode(v interface{}) string {
- jsonStr, _ := json.Marshal(v)
- return string(jsonStr)
- }
- // MD5加密
- func Md5(src string) string {
- m := md5.New()
- m.Write([]byte(src))
- res := hex.EncodeToString(m.Sum(nil))
- return res
- }
- func StructToGoutH(item interface{}) gout.H {
- result := make(gout.H)
- itemValue := reflect.ValueOf(item)
- // 如果传入的是指针,则获取其所指向的元素
- if itemValue.Kind() == reflect.Ptr {
- itemValue = itemValue.Elem()
- }
- // 确保传入的是结构体
- if itemValue.Kind() != reflect.Struct {
- return result
- }
- itemType := itemValue.Type()
- for i := 0; i < itemValue.NumField(); i++ {
- // 获取字段名和值
- field := itemType.Field(i)
- fieldValue := itemValue.Field(i).Interface()
- // 获取json标签,如果存在则使用json标签作为字段名
- jsonTag := field.Tag.Get("json")
- if jsonTag != "" && jsonTag != "-" {
- result[jsonTag] = fieldValue
- } else {
- result[field.Name] = fieldValue
- }
- }
- return result
- }
|