golang封装http get函数请求并且携带header头信息

有遇到这种需求,golang发送GET请求,携带header头信息,比如header里带着验证token

封装函数如下:

//Get请求携带header
func GetWithHeader(url string, headers map[string]string) (string, error) {
    client := &http.Client{}

    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return "", err
    }
    for key, header := range headers {
        req.Header.Set(key, header)
    }
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return "", err
    }
    return string(body), nil
}

使用方式如下:

    token := "aaaddddffffffffffffsssssssssss"
    id := 222
    headers := make(map[string]string)
    headers["Authorization"] = "bearer " + token
    result, _ := tools.GetWithHeader("/url?id="+id, headers)

 

posted @ 2022-11-03 15:02  唯一客服系统开发笔记  阅读(659)  评论(0编辑  收藏  举报