package demo
import (
"context"
"net/url"
"strconv"
"github.com/google/go-querystring/query"
)
// 解决的问题
//
// 当我们请求http接口时,如果接口参数超多,比如:
//
// 请求接口:https://api.example.com/v1/animal/list?query=示例&page=1&num=10&orderby=id&type=0
//
// 这是我们写代码时,会这样写
func GetAnimalListA(ctx context.Context, query, orderby string, page, num, animalType int) ([]interface{}, error) {
args := url.Values{}
args.Set("query", query)
args.Set("orderby", orderby)
args.Set("page", strconv.Itoa(page))
args.Set("num", strconv.Itoa(num))
args.Set("animal_type", strconv.Itoa(animalType))
// 把 args.Encode() 追加到接口后面继续请求...
return nil, nil
}
// 看上去函数参数超级多,且函数行也多
// 如果使用github.com/google/go-querystring/query ,代码就可以这样写:
type GetAnimalListReq struct {
Query string `url:"query"`
Orderby string `url:"orderby"`
Page int `url:"page"`
Num int `url:"num"`
AnimalType int `url:"animal_type"`
}
func GetAnimalListB(ctx context.Context, req *GetAnimalListReq) ([]interface{}, error) {
args, err := query.Values(req)
if err != nil {
return nil, err
}
// 把 args.Encode() 追加到接口后面继续请求...
return nil, nil
}
query包:将结构体转换成URL Query Strings
于 2024-11-26 17:10:51 首次发布