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

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

使用标准的http.Client,如何构建一个在http请求头中指定一个请求者的web请求?
下面你可以看到它是可以设置头,但你如何指定referer?是否仅通过设置Referer头?

  1. req, err := http.NewRequest("GET", url, nil)
  2. if err != nil {
  3. return "", err
  4. }
  5. req.Header.Set("Accept", "text/html,application/xhtml+xml")
  6. req.Header.Set("User-Agent", "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)")
  7. response, err1 := client.Get(url)
  8. if err1 != nil {
  9. return "", err1
  10. }
uttx8gqw

uttx8gqw1#

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

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

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

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

相关问题