doupo2241 2017-09-07 01:59
浏览 417
已采纳

如何在golang中指定http引荐来源网址?

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条回答 默认 最新

  • douqian9729 2017-09-07 05:17
    关注

    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 ""
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化