有遇到这种需求,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)
标签:http,string,err,get,nil,golang,header,headers From: https://www.cnblogs.com/taoshihan/p/16854503.html