[Go] Go语言实现post请求时发送header头信息

有些接口需要增加header头信息 , 里面传递token , 这个时候就要求在post的时候能传递自己的header信息

func PostHeader(url string, msg []byte, headers map[string]string) (string, error) {
    client := &http.Client{}

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

使用时

    url := "https://xxxxx/"
    headers := make(map[string]string)
    headers["Content-Type"] = "application/json;charset=utf-8"
    headers["token"] = token
    res, err := tools.PostHeader(url, []byte("dsdsddssdsd"), headers)

 

posted @ 2021-02-09 14:38  陶士涵  阅读(33)  评论(0编辑  收藏