如何获取HTTP重定向状态码

huangapple go评论162阅读模式
英文:

How to get the http redirect status codes

问题

我想要记录301和302重定向,但是在Client.Do、Get、doFollowingRedirects和CheckRedirect中,我看不到读取响应状态码的方法。我需要自己实现重定向来实现这个吗?

英文:

I'd like to log 301s vs 302s but can't see a way to read the response status code in Client.Do, Get, doFollowingRedirects, CheckRedirect. Will I have to implement redirection myself to achieve this?

答案1

得分: 13

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("请求", req.URL, "重定向,状态码为", resp.StatusCode)
    }
    return
}

(如果您只支持链接到默认传输方式,您可以简化这个代码块)。

然后,您可以使用这个传输方式创建一个客户端,任何重定向都会被记录:

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

这里有一个完整的示例供您参考:http://play.golang.org/p/8uf8Cn31HC

英文:

The http.Client type allows you to specify a custom transport, which should allow you to do what you're after. Something like the following should do:

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
}

(you could simplify this a little if you only support chaining to the default transport).

You can then create a client using this transport, and any redirects should be logged:

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

Here is a full example you can experiment with: http://play.golang.org/p/8uf8Cn31HC

huangapple
  • 本文由 发表于 2014年7月4日 23:33:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/24577494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定