51 lines
1.3 KiB
Go
51 lines
1.3 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"net/url"
|
|
"reflect"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func GetUrlFormedMap(source map[string]string) (urlEncoded string) {
|
|
urlEncoder := url.Values{}
|
|
for key, value := range source {
|
|
urlEncoder.Add(key, value)
|
|
}
|
|
urlEncoded = urlEncoder.Encode()
|
|
return
|
|
}
|
|
|
|
func InitStructWithDefaultTag(bean interface{}) {
|
|
beantype := reflect.TypeOf(bean)
|
|
for i := 0; i < beantype.Elem().NumField(); i++ {
|
|
field := beantype.Elem().Field(i)
|
|
defaultValue := strings.TrimSpace(field.Tag.Get("default"))
|
|
if defaultValue == "" || defaultValue == "-" {
|
|
continue
|
|
}
|
|
setter := reflect.ValueOf(bean).Elem().Field(i)
|
|
fieldTypeName := field.Type.String()
|
|
switch fieldTypeName {
|
|
case "int", "int64", "int32", "int8", "int16":
|
|
intval, _ := strconv.ParseInt(defaultValue, 10, 64)
|
|
setter.SetInt(intval)
|
|
case "uint", "uint8", "uint16", "uint32", "uint64", "uintptr":
|
|
uintval, _ := strconv.ParseUint(defaultValue, 10, 64)
|
|
setter.SetUint(uintval)
|
|
case "string":
|
|
setter.SetString(defaultValue)
|
|
case "time.Duration":
|
|
intval, _ := strconv.ParseInt(defaultValue, 10, 64)
|
|
setter.SetInt(intval * int64(time.Second))
|
|
case "bool":
|
|
boolval, _ := strconv.ParseBool(defaultValue)
|
|
setter.SetBool(boolval)
|
|
default:
|
|
fmt.Println(field.Type.String(), field.Name)
|
|
}
|
|
}
|
|
}
|