解析 Github 响应以获取访问令牌。

huangapple go评论101阅读模式
英文:

Parsing Github response for access_token

问题

只是在玩弄Github API和oauth。我已经到达了从GH接收access_token的阶段。

到目前为止,我有:

url := "https://github.com/login/oauth/access_token"

params := map[string]string{"client_id": client_id, "client_secret": client_secret, "code": code}
data, _ := json.Marshal(params)
resp, _ := http.Post(url, "application/json", bytes.NewBuffer(data))

defer resp.Body.Close()
    
body, _ := ioutil.ReadAll(resp.Body)

但是我现在想访问响应的部分。根据GH文档,它们的形式是
access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&scope=user%2Cgist&token_type=bearer

我需要解析字符串吗,还是有一个"更好"的方法?

英文:

Just messing around with Github API and oauth. I have got to the point where I receive the access_token back from GH.

I have so far:

url := "https://github.com/login/oauth/access_token"

params := map[string]string{"client_id": client_id, "client_secret": client_secret, "code": code}
data, _ := json.Marshal(params)
resp, _ := http.Post(url, "application/json", bytes.NewBuffer(data))

defer resp.Body.Close()
    
body, _ := ioutil.ReadAll(resp.Body)

but I would now like to access the response parts. According to the GH docs, they are in the form
access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&scope=user%2Cgist&token_type=bearer

Do I need to parse the string or is there a "better" way?

答案1

得分: 3

这是一个URL查询字符串。你可以使用url包来解析它,并得到一个url.Values(就是一个映射)。

resp := "access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&scope=user%2Cgist&token_type=bearer"
values, err := url.ParseQuery(resp)
if err != nil {
	panic(err)
}

fmt.Println("access_token:", values["access_token"])
fmt.Println("token_type:", values["token_type"])

Play链接

英文:

This is a URL query string. You can use the url package to parse it and get a url.Values (which is just a map) out.

resp := "access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&scope=user%2Cgist&token_type=bearer"
values, err := url.ParseQuery(resp)
if err != nil {
	panic(err)
}

fmt.Println("access_token:", values["access_token"])
fmt.Println("token_type:", values["token_type"])

Play link

huangapple
  • 本文由 发表于 2015年10月7日 04:28:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/32979138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定