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

36 lines
855 B
Go

package utils
import (
"fmt"
"net/url"
"reflect"
)
func StructToURLValues(s interface{}) (url.Values, error) {
values := url.Values{}
structValue := reflect.ValueOf(s)
structFieldValue := structValue.FieldByName
structType := reflect.TypeOf(s)
for i := 0; i < structType.NumField(); i++ {
fieldName := structType.Field(i).Name
tagName := structType.Field(i).Tag.Get("form")
valueField := fieldName
if tagName != "" {
valueField = tagName
}
fieldValue := structFieldValue(fieldName)
switch fieldValue.Kind() {
case reflect.String:
values.Set(valueField, fieldValue.String())
case reflect.Int, reflect.Int64:
str := fmt.Sprintf("%v", fieldValue.Int())
values.Set(valueField, str)
default:
return nil, fmt.Errorf("unsupported field type: %v", fieldValue.Kind())
}
}
fmt.Println(values)
return values, nil
}