代码之家  ›  专栏  ›  技术社区  ›  Jay

如何在golang中指定http引用?

  •  3
  • Jay  · 技术社区  · 7 年前

    使用标准http。客户端,如何构建在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
    }
    
    1 回复  |  直到 7 年前
        1
  •  8
  •   VonC    7 年前

    是的,正如你从围棋本身的来源中所看到的,在 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 ""
    }