How do you specify the http referrer in golang?

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

How do you specify the http referrer in golang?

问题

使用标准的http.Client,您可以如下构建一个包含引用来源的Web请求:

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)")
req.Header.Set("Referer", "http://example.com")

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

在上述代码中,通过调用req.Header.Set("Referer", "http://example.com")来设置引用来源。然后,您可以使用client.Do(req)来发送请求并获取响应。

英文:

Using the standard http.Client, how do you build a web request that specifies a referrer in the http request header?

Below you can see it is possible to set headers, but how do you specify the referer? Is it just by setting a Referer header?

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

得分: 8

是的,根据Go本身的源代码,可以看到在src/net/http/client.go中有以下内容:

// 如果不是https->http,则将最近的请求URL的Referer头添加到新的请求中
if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL); ref != "" {
    req.Header.Set("Referer", ref)
}

但是请注意你的scheme,在同样的源代码中有以下内容:

// refererForURL函数返回一个不包含任何身份验证信息的referer,
// 如果lastReq的scheme是https且newReq的scheme是http,则返回空字符串
func refererForURL(lastReq, newReq *url.URL) string {
	// https://tools.ietf.org/html/rfc7231#section-5.5.2
	//   "如果引用页面是通过安全协议传输的,则在(非安全的)HTTP请求中,
	//    客户端不应包含Referer头字段。"
	if lastReq.Scheme == "https" && newReq.Scheme == "http" {
		return ""
}
英文:

Yes, as you can see from the sources from Go itself, in 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)
}

Check your scheme though, 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 ""
}

huangapple
  • 本文由 发表于 2017年9月7日 09:59:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/46086746.html
匿名

发表评论

匿名网友

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

确定