你如何在golang中指定http referrer?

时间:2017-09-07 01:59:56

标签: http go referrer

使用标准的http.Client,如何在http请求标头中构建指定引用者的Web请求?

下面你可以看到可以设置标题,但是你如何指定引用?只是通过设置Referer标题吗?

req, err := http.NewRequest("GET", url, nil)
if err != nil {
    return "", err
}
req.Header.Set("Accept", "text/html,application/xhtml+xml")
req.Header.Set("User-Agent", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)")

response, err1 := client.Get(url)
if err1 != nil {
    return "", err1
}

1 个答案:

答案 0 :(得分:5)

是的,正如你可以从Go本身的来源看到的,src/net/http/client.go

// Add the Referer header from the most recent
// request URL to the new one, if it's not https->http:
if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL); ref != "" {
    req.Header.Set("Referer", ref)
}

检查您的方案,as in the same sources

// refererForURL returns a referer without any authentication info or
// an empty string if lastReq scheme is https and newReq scheme is http.
func refererForURL(lastReq, newReq *url.URL) string {
    // https://tools.ietf.org/html/rfc7231#section-5.5.2
    //   "Clients SHOULD NOT include a Referer header field in a
    //    (non-secure) HTTP request if the referring page was
    //    transferred with a secure protocol."
    if lastReq.Scheme == "https" && newReq.Scheme == "http" {
        return ""
}