doucezhu3570 2018-08-01 08:33
浏览 12
已采纳

如何从http.Client添加默认标题字段

I want http.Client to add additional header for all requests.

type MyClient struct {
    http.Client
}

func (c *MyClient) Do(req *http.Request) (*http.Response, error) {
    req.Header.Add("User-Agent", "go")
    return c.Client.Do(req)
}

func Do never gets called if I call func PostForm that is using Do. If there is no way how to mimic OOP, how to do it least painfully?

  • 写回答

1条回答 默认 最新

  • dse84825 2018-08-01 09:07
    关注

    http.Client has a field Transport which is of type RoundTripper - an interface type.

    It provides us the option to change request (and response, of course) between.

    You can create a custom type that wraps another RoundTripper and adds the header in the custom type's RoundTrip:

    type AddHeaderTransport struct{
        T http.RoundTripper
    }
    
    func (adt *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response,error) {
        req.Header.Add("User-Agent", "go")
        return adt.T.RoundTrip(req)
    }
    

    Full code on playground: https://play.golang.org/p/FbkpFlyFCm_F

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器