2017-09-07 48 views
0

使用標準的http.client,你如何建立一個Web請求,在http請求頭中指定一個referrer?如何在golang中指定http referrer?

下面你可以看到可以設置標題,但是你如何指定引用者?只是通過設置一個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 
} 
+2

HTTPS://tools.ietf。 org/html/rfc2616#section-14.36 –

+7

是的,Referer是標題。你嘗試過設置它嗎? – JimB

+0

@JimB如果我知道如何設置它,我不需要問這個問題。 :d – Jacob

回答

2

是的,你可以從圍棋本身的來源看,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 "" 
}