doubei2231 2016-09-16 09:19
浏览 43
已采纳

Go HTTP客户端是否有“中间件”?

I would like to ask if we can create 'middleware' functions for Go http client? Example I want to add a log function, so every sent request will be logged, or add setAuthToken so the token will be added to each request's header.

  • 写回答

2条回答 默认 最新

  • doufan6886 2016-09-16 10:01
    关注

    You can use the Transport parameter in HTTP client to that effect, with a composition pattern, using the fact that:

    • http.Client.Transport defines the function that will handle all HTTP requests;
    • http.Client.Transport has interface type http.RoundTripper, and can thus be replaced with your own implementation;

    For example:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    // This type implements the http.RoundTripper interface
    type LoggingRoundTripper struct {
        Proxied http.RoundTripper
    }
    
    func (lrt LoggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) {
        // Do "before sending requests" actions here.
        fmt.Printf("Sending request to %v
    ", req.URL)
    
        // Send the request, get the response (or the error)
        res, e = lrt.Proxied.RoundTrip(req)
    
        // Handle the result.
        if (e != nil) {
            fmt.Printf("Error: %v", e)
        } else {
            fmt.Printf("Received %v response
    ", res.Status)
        }
    
        return
    }
    
    func main() {
        var c = &http.Client{Transport:LoggingRoundTripper{http.DefaultTransport}}
        c.Get("https://www.google.com")
    }
    

    Feel free to alter names as you wish, I did not think on them for very long.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line