Go http客户端有"中间件"吗?

qua*_*n88 4 go

我想问一下我们是否可以为Go http客户端创建"中间件"功能?示例我想添加一个日志功能,因此将记录每个发送的请求,或添加setAuthToken,以便将令牌添加到每个请求的标头中.

Jea*_*nal 13

您可以使用Transport以下事实将HTTP客户端中的参数用于具有组合模式的效果:

  • http.Client.Transport 定义将处理所有HTTP请求的函数;
  • http.Client.Transport具有接口类型http.RoundTripper,因此可以用您自己的实现替换;

例如:

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\n", 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\n", res.Status)
    }

    return
}

func main() {
    var c = &http.Client{Transport:LoggingRoundTripper{http.DefaultTransport}}
    c.Get("https://www.google.com")
}
Run Code Online (Sandbox Code Playgroud)

随意改变你想要的名字,我没想到它们很长时间.