如何在golang中指定http referrer作为客户端?

jjjwad0x  于 2023-09-28  发布在  Go
关注(0)|答案(1)|浏览(105)

使用标准的http.Client,如何构建一个在http请求头中指定一个请求者的web请求?
下面你可以看到它是可以设置头,但你如何指定referer?是否仅通过设置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
}
uttx8gqw

uttx8gqw1#

是的,正如你可以从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)
}

检查您的方案,如在相同的来源:

// 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 ""
}

相关问题