2016-11-26 51 views
1

我正在爲我的程序編寫一個測試套件,用於從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)) 
} 

回答

2

您的curl命令未設置空的Authorization標頭;那curl命令將排除Authorization標頭。您可以通過添加-v參數進行驗證:

curl -H "Authorization: " -v "https://api.github.com/repos/octocat/Hello-World/issues?state=open&per_page=1&page=1" 

話雖這麼說,你不應該在你的Go代碼設置Authorization頭無論是。所以,只需刪除該行,並且您的代碼立即生效。

+0

感謝您關於捲曲的提示。我需要在Go代碼中保留該行,因爲我需要爲我的測試傳入多個標記。但考慮到你所說的話,我想我會寫一個條件來排除設置標題,如果我沒有令牌。謝謝,我會盡快接受你的答案。 – nosequeldeebee