手动fmt.Sprinf可以吗,可以啊,我没说不行啊嘿嘿
// buildURL 拼接请求参数到路由 func buildURL(path string, params map[string]string) (string, error) { paramMap := url.Values{} for k, v := range params { paramMap.Set(k, v) } base, err := url.Parse(path) if err != nil { return "", err } base.RawQuery = paramMap.Encode() return base.String(), nil }
单元测试
func Test_buildURL(t *testing.T) { type args struct { path string params map[string]string } tests := []struct { name string args args want string wantErr bool }{ { name: "测试拼接", args: args{ path: "www.baidu.com?name=jack", params: map[string]string{ "age": "18", }, }, want: "", wantErr: false, }, { name: "测试拼接", args: args{ path: "www.baidu.com?name=jack", params: map[string]string{ "age": "18", "name": "rose", }, }, want: "", wantErr: false, }, { name: "测试拼接", args: args{ path: "www.baidu.com?h#y", params: map[string]string{ "age": "18", "name": "rose", }, }, want: "", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := buildURL(tt.args.path, tt.args.params) if (err != nil) != tt.wantErr { t.Errorf("buildURL() error = %v, wantErr %v", err, tt.wantErr) return } t.Logf("got=%s", got) }) } }
可以自动处理一下#参数以及重复的query参数,单元测试输出:
=== RUN Test_buildURL === RUN Test_buildURL/测试拼接 http_test.go:64: got=www.baidu.com?age=18 === RUN Test_buildURL/测试拼接#01 http_test.go:64: got=www.baidu.com?age=18&name=rose === RUN Test_buildURL/测试拼接#02 http_test.go:64: got=www.baidu.com?age=18&name=rose#y --- PASS: Test_buildURL (0.00s) --- PASS: Test_buildURL/测试拼接 (0.00s) --- PASS: Test_buildURL/测试拼接#01 (0.00s) --- PASS: Test_buildURL/测试拼接#02 (0.00s)
标签:string,URL,args,Test,拼接,buildURL,Params,GO,name From: https://www.cnblogs.com/xuweiqiang/p/16944695.html