无法使用Golang获取Box API的访问令牌。

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

Not able to get access token for box api using golang

问题

我无法使用golang获取Box API的访问令牌。

以下是我的代码:

// box项目的main.go文件

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

type accessinfo struct {
	access_token  string
	expires_in    int64
	token_type    string
	refresh_token string
}

var accessobj accessinfo

func try(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "hello,world!\n")
	if r.Method == "GET" {
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte("This is an example.\n"))
		code := r.FormValue("code")
		fmt.Println("gvshnbc")
		fmt.Println(code)
		authToken(code)
		dat, err := ioutil.ReadAll(r.Body)
		if dat == nil {
			log.Print("no data")
		}
		log.Print(string(dat))
		if err != nil {
			log.Print("no error")
		}
	}
}

func authToken(code string) {
	apiUrl := "https://app.box.com/api"
	data := url.Values{}
	data.Set("grant_type", "authorization_code")
	data.Add("code", code)
	fmt.Println(code)
	data.Add("client_id", "rnk5pqyahzrkf6bxwtc79rcief8u76p6")
	data.Add("client_secret", "7xbeJvi76oc0IcHmfcUzZZPP9b0jVbDs")
	u, _ := url.ParseRequestURI(apiUrl)
	fmt.Println(u)
	urlStr := fmt.Sprintf("%v", u)
	fmt.Println(urlStr)
	client := &http.Client{}
	r, err := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))
	if err != nil {
		panic(err)
	}
	fmt.Println(r)
	if err != nil {
		fmt.Println(err)
	}
	resp, err := client.Do(r)
	if err != nil {
		fmt.Println(err)
	}
	re, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("error")
		fmt.Println(string(re))
	}
	a := json.Unmarshal(re, &accessobj)
	fmt.Println(a)
}

希望这能帮到你!

英文:

I am not able to get access token for box api using golang.

Here's my code:

// box project main.go
package main
import ("bytes" "encoding/json" "fmt" "io" "io/ioutil" "log" "net/http" "net/url"
)
type accessinfo struct {access_token  string expires_in   int64 token_type    string refresh_token string}
var accessobj accessinfo
func try(w http.ResponseWriter, r *http.Request) {io.WriteString(w, "hello,world!\n")if r.Method == "GET" {w.Header().Set("Content-Type", "text/plain")w.Write([]byte("This is an example.\n"))code := r.FormValue("code")fmt.Println("gvshnbc")fmt.Println(code)authToken(code)dat, err := ioutil.ReadAll(r.Body)if dat == nil {log.Print("no data")} log.Print(string(dat))if err != nil {log.Print("no error")}}}func authToken(code string) {apiUrl := "https://app.box.com/api"///resource := "/oauth2/token"    data := url.Values{    data.Set("grant_type", "authorization_code")data.Add("code", code)fmt.Println(code) data.Add("client_id", "rnk5pqyahzrkf6bxwtc79rcief8u76p6")//data.Add("redirect_uri", "http://localhost:8089")data.Add("client_secret", "7xbeJvi76oc0IcHmfcUzZZPP9b0jVbDs")//data.Add("state", "authenticated") //fmt.Println(data)    u, _ := url.ParseRequestURI(apiUrl)//    u.Path = resource
fmt.Println(u)    urlStr := fmt.Sprintf("%v", u)    fmt.Println(urlStr)    client := &http.Client{}    //fmt.Println(client)    r, err := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode()))    if err != nil {        panic(err)
//break    }    //r.Header.Add("Content-Type", "application/x-www-form-urlencoded")    //r.Header.Add("Content-Length", "9")fmt.Println(r)    if err != nil {        fmt.Println(err)    }
//fmt.Println(bytes.NewBufferString(data.Encode()))//fmt.Println(data.Encode())//fmt.Println(r)resp, err := client.Do(r)    if err != nil {        fmt.Println(err)    }    //fmt.Println(resp)    re, err := ioutil.ReadAll(resp.Body)    if err != nil {        fmt.Println("error")        fmt.Println(string(re))    }a := json.Unmarshal(re, &accessobj)fmt.Println(a)}

答案1

得分: 1

首先,你可能想要从你发布的代码中删除你的ClientID和ClientSecret。

其次,你最好使用已经存在的OAuth2实现(code.google.com/p/goauth2/oauth 是相当不错的选择)。

至于你的代码为什么不起作用,你贴出的代码不是完整的Go代码(缺少了几个闭合的大括号 - data := url.Values{ 没有闭合)。此外,你应该定义一个main函数 - 没有它,你的Go代码将无法运行(除非有其他使用此代码的代码,但上面没有贴出)。如果你想要一个能够工作的获取Box API令牌的Go代码示例(我在这里做个自我推销),我写了一些用于初步的Go Box客户端的代码(只是我一直没有完成它)。这个小的main函数将帮助你获取一个令牌:https://github.com/ttacon/box/blob/master/boxtoken/boxtoken.go。

要运行它,只需进入所在的目录,并使用以下命令运行:

go run boxtoken.go -cid=YOUR_CLIENT_ID -csec=YOUR_CLIENT_SECRET

然后只需访问 http://localhost:8080/ 并按照页面上的说明进行操作。

希望能对你有所帮助!

英文:

First off, you might want to remove your ClientID and ClientSecret from the code you posted.

Second, you'd probably be better off using an OAuth2 implementation that already exists code.google.com/p/goauth2/oauth is pretty good).

As to why your code doesn't work, the code you pasted isn't complete go code (it's missing a couple closing curly braces - data := url.Values{ is unclosed). Also, you should define a main function - without it your go code isn't going to run (unless there is other code using this code, that wasn't pasted above). If you want an example of go code that works to get a Box API token (shameless plug here), I wrote a bunch of stuff for a preliminary Box Client in go (I just never got around to finishing it). This little main will help you get a token: https://github.com/ttacon/box/blob/master/boxtoken/boxtoken.go.

To run it just cd into the directory it is in and run it with:

go run boxtoken.go -cid=YOUR_CLIENT_ID -csec=YOUR_CLIENT_SECRET

Then just go to http://localhost:8080/ and follow the page.

Hope that helps!

huangapple
  • 本文由 发表于 2015年2月13日 20:41:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/28499863.html
匿名

发表评论

匿名网友

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

确定