4.1
重定向
默认的 HTTP 客户端会自动且静默地跟踪重定向最多 10 次,之后它会终止。
The custom function to implement the redirect policy must satisfy the following signature:
func (req *http.Request, via []*http.Request) errorThe first argument, req, is the request to follow the redirect response that it got back from the server; the slice, via, contains the requests that have been made so far, with the oldest request (your original request) the first element of this slice.
函数返回nil则追踪重定向(client重发请求),返回error则终止重定向。
比如要终止重定向:
func redirectPolicyFunc(req *http.Request, via []*http.Request) error {
if len(via)>= 1 {
return errors.New("stopped after 1 redirect")
}
return nil
}
func createHTTPClientWithTimeout(d time.Duration) *http.Client {
return &http.Client{
Timeout: d,
CheckRedirect: redirectPolicyFunc
}
}5
在context中保存键值对,要确保:
-
键不应是基本类型之一,如 string
-
应定义自己的未导出类型作为键,如
type requestContextKey struct{} type requestContextValue struct { requestID string }