douwei2966 2016-11-26 21:10
浏览 27
已采纳

如何在Go中设置空授权标头?

I am writing a test suite for my program that fetches data from Github APIs. I need to set an empty authentication header. It works fine with curl but doesn't work in my Go program.

I tried setting it to "null" as suggested here. I've also tried nil, "" which don't work.

The output (too long to copy here but you can try it yourself) is as expected with curl -H "Authorization: " "https://api.github.com/repos/octocat/Hello-World/issues?state=open&per_page=1&page=1"

But here is the output with the same empty header set in Go:

{"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"}

Here is the code (please don't suggest that I just remove the req.Header.Set() line. I need to keep it in for my test suite)

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))
}
  • 写回答

1条回答 默认 最新

  • dongxi5494 2016-11-26 21:19
    关注

    Your curl command does not set an empty Authorization header; that curl command will exclude the Authorization header. You can verify it by adding the -v parameter:

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

    That being said, you shouldn't set Authorization header in your Go code either. So just remove that line, and your code becomes working immediately.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要