golang http.Post请求返回响应404

时间:2018-12-01 10:52:57

标签: http go http-post github-api

我在github仓库中编写了一个go代码来在项目中创建问题。我正在使用此处提到的参数[https://developer.github.com/v3/issues/#create-an-issue][1]

但是我收到状态404的响应。下面是我的代码。

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    param := map[string]string{"title": "issue1", "body": "aassddrff", "assignee": "vigneshkm"}

    query, _ := json.Marshal(param)
    queryUrl := "https://api.github.com/repos/vigneshkm/first_repo/issues"

    fmt.Println("query:", string(query))
    resp, err := http.Post(queryUrl, "application/json", bytes.NewBuffer(query))

    fmt.Println("query_status : ", resp.StatusCode, "err : ", err)
    resp.Body.Close()
}

我是Web编程的初学者,我无法理解此代码中的错误。请帮助我:)

2 个答案:

答案 0 :(得分:0)

您在请求时缺少访问令牌。

queryUrl := "https://api.github.com/repos/vigneshkm/first_repo/issues?access_token=" + OAUTH_TOKEN

选中此document

答案 1 :(得分:0)

1)访问https://github.com/settings/tokens
2)点击“生成新令牌”
3)复制令牌。
4)将令牌粘贴到下面的“ YOUR_ACCESS_TOKEN_HERE”。 (我的意思是,删除“ YOUR_ACCESS_TOKEN_HERE”并在其中粘贴令牌)。

$ cat main.go 
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    param := map[string]string{"title": "issue1", "body": "aassddrff", "assignee": "vigneshkm"}

    query, _ := json.Marshal(param)
    queryUrl := "https://api.github.com/repos/vigneshkm/first_repo/issues?access_token=YOUR_ACCESS_TOKEN_HERE"

    fmt.Println("query:", string(query))
    resp, err := http.Post(queryUrl, "application/json", bytes.NewBuffer(query))

    fmt.Println("query_status : ", resp.StatusCode, "err : ", err)
    resp.Body.Close()
}

这是我环境中的结果。

$ go run main.go 
query: {"assignee":"vigneshkm","body":"aassddrff","title":"issue1"}
query_status :  201 err :  <nil>

https://github.com/vigneshkm/first_repo/issues/2