1 Star 0 Fork 0

cruller/gummy

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
parames.go 2.41 KB
一键复制 编辑 原始数据 按行查看 历史
package gummy
import (
"fmt"
"net/url"
"reflect"
)
func pkgGetURLParames(rawURL string, parames ...interface{}) string {
count := len(parames)
switch {
case count == 1:
val := parames[0]
if val, dup := val.(map[string]interface{}); dup {
rawURL = pkgGetMapParames(rawURL, val)
break
}
var kind reflect.Kind
if kind = reflect.TypeOf(val).Kind(); kind == reflect.Ptr {
tmp := reflect.ValueOf(val).Elem()
kind = tmp.Kind()
val = tmp.Interface()
}
if kind == reflect.Struct {
rawURL = pkgGetStructParames(rawURL, val)
break
}
fallthrough
case count > 1:
lastVal := parames[len(parames)-1]
lastValIsParames := false
if arg, dup := lastVal.(map[string]interface{}); dup {
if arg != nil {
lastValIsParames = true
}
} else {
typ := reflect.TypeOf(lastVal)
val := reflect.ValueOf(lastVal)
kind := typ.Kind()
if kind == reflect.Struct {
lastValIsParames = true
} else if kind == reflect.Ptr && !val.IsNil() && typ.Elem().Kind() == reflect.Struct {
lastValIsParames = true
}
}
if lastValIsParames {
parames = parames[:len(parames)-1]
}
rawURL = fmt.Sprintf(rawURL, parames...)
if lastValIsParames {
return pkgGetURLParames(rawURL, lastVal)
}
}
return rawURL
}
func pkgGetMapParames(rawURL string, args map[string]interface{}) string {
u, _ := url.Parse(rawURL)
q := u.Query()
for k, v := range args {
q.Add(k, fmt.Sprintf("%v", v))
}
u.RawQuery = q.Encode()
return u.String()
}
func pkgGetStructParames(rawURL string, args interface{}) string {
u, _ := url.Parse(rawURL)
q := u.Query()
typ := reflect.TypeOf(args)
val := reflect.ValueOf(args)
count := typ.NumField()
for i := 0; i < count; i++ {
k := typ.Field(i)
v := val.Field(i).Interface()
q.Add(lowParamesName(k.Name), fmt.Sprintf("%v", v))
}
u.RawQuery = q.Encode()
return u.String()
}
func lowParamesName(name string) string {
count := len(name)
newName := make([]byte, 1, len(name)*2)
newName[0] = toLow(name[0])
for i := 1; i < count; i++ {
ch := name[i]
if isUp(ch) {
if isUp(name[i-1]) {
newName = append(newName, toLow(ch))
} else {
newName = append(newName, '_', toLow(ch))
}
} else {
newName = append(newName, ch)
}
}
return string(newName)
}
func isUp(ch byte) bool {
return ch >= 'A' && ch <= 'Z'
}
func isLow(ch byte) bool {
return ch >= 'a' && ch <= 'z'
}
func toLow(ch byte) byte {
if isUp(ch) {
return ch + 32
}
return ch
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/cruller/gummy.git
git@gitee.com:cruller/gummy.git
cruller
gummy
gummy
main

搜索帮助