如何在Golang中获取http重定向状态代码

如何在Golang中获取http重定向状态代码,第1张

如何在Golang中获取http重定向状态代码

http.Client
类型允许您指定自定义传输方式,这应允许您执行后续 *** 作。应该执行以下 *** 作:

type LogRedirects struct {    Transport http.RoundTripper}func (l LogRedirects) RoundTrip(req *http.Request) (resp *http.Response, err error) {    t := l.Transport    if t == nil {        t = http.DefaultTransport    }    resp, err = t.RoundTrip(req)    if err != nil {        return    }    switch resp.StatusCode {    case http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusTemporaryRedirect:        log.Println("Request for", req.URL, "redirected with status", resp.StatusCode)    }    return}

(如果仅支持链接到默认传输,则可以稍微简化一下)。

然后,您可以使用此传输方式创建客户端,并记录所有重定向:

client := &http.Client{Transport: LogRedirects{}}

这是您可以尝试的完整示例:http :
//play.golang.org/p/8uf8Cn31HC



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5048995.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存