7
0
gaore-common-sdk-go/sdk/utils/utils.go

51 lines
1.3 KiB
Go
Raw Normal View History

2020-08-04 00:51:19 +08:00
package utils
2020-08-04 21:14:06 +08:00
import (
"fmt"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
2020-08-04 00:51:19 +08:00
func GetUrlFormedMap(source map[string]string) (urlEncoded string) {
urlEncoder := url.Values{}
for key, value := range source {
urlEncoder.Add(key, value)
}
urlEncoded = urlEncoder.Encode()
return
}
2020-08-04 21:14:06 +08:00
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)
}
}
}