93 lines
2.2 KiB
Go
93 lines
2.2 KiB
Go
package common
|
||
|
||
import (
|
||
"crypto/md5"
|
||
"crypto/tls"
|
||
"encoding/hex"
|
||
"fmt"
|
||
"github.com/go-resty/resty/v2"
|
||
"io"
|
||
"mime/multipart"
|
||
"reflect"
|
||
"strconv"
|
||
"time"
|
||
)
|
||
|
||
func GetRestyRequest() *resty.Request {
|
||
client := resty.New().SetTimeout(time.Duration(5) * time.Second)
|
||
client.SetTLSClientConfig(&tls.Config{
|
||
InsecureSkipVerify: true, // Only for development/testing
|
||
})
|
||
request := client.R()
|
||
return request
|
||
}
|
||
|
||
func GetFileMd5(file multipart.File) (string, error) {
|
||
hash := md5.New()
|
||
if _, err := io.Copy(hash, file); err != nil {
|
||
return "", err
|
||
}
|
||
|
||
// 计算MD5并转换为16进制字符串
|
||
md5Bytes := hash.Sum(nil)
|
||
md5Str := hex.EncodeToString(md5Bytes)
|
||
return md5Str, nil
|
||
}
|
||
|
||
func Bool2String(b bool) string {
|
||
return strconv.FormatBool(b)
|
||
}
|
||
|
||
// StructToMapWithTag 将结构体转换为 map[string]string,key 使用指定标签的值
|
||
func StructToMapWithTag(obj interface{}, tagName string) (map[string]string, error) {
|
||
result := make(map[string]string)
|
||
|
||
// 获取值的反射对象
|
||
val := reflect.ValueOf(obj)
|
||
if val.Kind() == reflect.Ptr {
|
||
val = val.Elem() // 解引用指针
|
||
}
|
||
|
||
if val.Kind() != reflect.Struct {
|
||
return nil, fmt.Errorf("input is not a struct or pointer to struct")
|
||
}
|
||
|
||
// 获取类型信息
|
||
typ := val.Type()
|
||
|
||
// 遍历结构体字段
|
||
for i := 0; i < val.NumField(); i++ {
|
||
field := val.Field(i)
|
||
fieldType := typ.Field(i)
|
||
|
||
// 获取字段的标签值
|
||
tagValue := fieldType.Tag.Get(tagName)
|
||
if tagValue == "" {
|
||
continue // 如果标签不存在,跳过该字段
|
||
}
|
||
|
||
// 获取字段值并转换为字符串
|
||
var fieldValue string
|
||
switch field.Kind() {
|
||
case reflect.String:
|
||
fieldValue = field.String()
|
||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||
fieldValue = strconv.FormatInt(field.Int(), 10)
|
||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||
fieldValue = strconv.FormatUint(field.Uint(), 10)
|
||
case reflect.Float32, reflect.Float64:
|
||
fieldValue = strconv.FormatFloat(field.Float(), 'f', -1, 64)
|
||
case reflect.Bool:
|
||
fieldValue = strconv.FormatBool(field.Bool())
|
||
default:
|
||
// 如果字段类型不支持,跳过
|
||
continue
|
||
}
|
||
|
||
// 将标签值和字段值存入 map
|
||
result[tagValue] = fieldValue
|
||
}
|
||
|
||
return result, nil
|
||
}
|