我正在爲我的程序編寫一個測試套件,用於從Github API獲取數據。我需要設置一個空的驗證標題。它適用於curl
,但在我的Go程序中不起作用。如何在Go中設置空授權標頭?
我試着將它設置爲「null」,建議here。我也試過nil
,""
哪些行不通。
輸出(太長複製到這裏,但你可以自己嘗試一下)是與curl -H "Authorization: " "https://api.github.com/repos/octocat/Hello-World/issues?state=open&per_page=1&page=1"
預期,但這裏是用相同的空頭部在Go設置輸出:
{"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"}
這裏是代碼(請不要建議我只是刪除req.Header.Set()
行,我需要保留在我的測試套件中)
func main() {
client := &http.Client{}
//issues API from Github
req, err := http.NewRequest("GET", "https://api.github.com/repos/octocat/Hello-World/issues?state=open&per_page=1&page=1", nil)
if err != nil {
log.Fatal(err)
}
//set authorization header. I have tried nil, and ""
req.Header.Set("Authorization", "null")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
//convert to a usable slice of bytes
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("couldn't read issues list", err)
}
fmt.Println(string(body))
}
感謝您關於捲曲的提示。我需要在Go代碼中保留該行,因爲我需要爲我的測試傳入多個標記。但考慮到你所說的話,我想我會寫一個條件來排除設置標題,如果我沒有令牌。謝謝,我會盡快接受你的答案。 – nosequeldeebee