2025-01-21 16:36:20 +08:00

55 lines
1.4 KiB
Go

package util
import (
"errors"
"fmt"
"net/url"
"reflect"
"strings"
)
// StructToQueryParams 将struct转换为queryString
func StructToQueryParams(s interface{}) (string, error) {
params := url.Values{}
val := reflect.ValueOf(s)
// 确保传入的是一个结构体指针
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
// 确保传入的是一个结构体
if val.Kind() != reflect.Struct {
return "", fmt.Errorf("input must be a struct or struct pointer")
}
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldName := typ.Field(i).Name
if tag := typ.Field(i).Tag.Get("json"); fieldName != "" {
arr := strings.Split(tag, ",")
if len(arr) > 1 {
fieldName = arr[0]
if arr[1] == "omitempty" && field.IsZero() {
continue
}
}
}
// 对于基本类型,添加到 url.Values 中
switch field.Kind() {
case reflect.String:
params.Add(fieldName, field.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
params.Add(fieldName, fmt.Sprint(field.Int()))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
params.Add(fieldName, fmt.Sprint(field.Uint()))
case reflect.Float32, reflect.Float64:
params.Add(fieldName, fmt.Sprint(field.Float()))
// 可以根据需要添加更多的类型支持
default:
return "", errors.New("unsupport type")
}
}
return params.Encode(), nil
}