query包:将结构体转换成URL Query Strings

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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值