首页 > 解决方案 > 我想知道Gin Framwork函数,类似于http.Get和http.Post

问题描述

在开发 Oauth 授权中,我遇到了绑定问题

var googleOauthConfig = &model.OauthConfig{
    Client_id:     os.Getenv("webclient_id"),
    Client_secret: "",
    Redirect_uri:  info.GoogleRedirectPath,
    Grant_type:    "authorization_code",
}
const RequestGoogleToken string = "https://accounts.google.com/o/oauth2/v2/auth"

type Token struct {
    Access_token  string    `json:"access_token" binding:"required"`
    Token_type    string    `json:"token_type" binding:"required"`
    Expiration    time.Time `json:"expires_in" binding:"required"`
    Refresh_token string    `json:"refresh_token" binding:"required"`
}

我必须在 RequestGoogleToken URI 中请求方法“POST”并获取令牌结构数据

我可以用这种方式

token := &model.Token{}
pbytes, _ := json.Marshal(token)
buff := bytes.NewBuffer(pbytes)
resp, err := http.Post(info.RequestGoogleToken, "application/json", buff)

我使用了 http 函数“POST”,我可以获取 []byte 的数据类型,但我无法绑定 Token Struct

我想要杜松子酒框架方法,如果您提出任何想法,我将不胜感激

标签: gooauth-2.0oauthbind

解决方案


我遇到了同样的问题,我找不到任何杜松子酒的内部功能来满足它(也许我的研究不完整)。但这是我的处理方式。您可以使用带有 json.NewDecoder 的 map[string]interface{} 来了解一下:

 resp, err := http.Get("https://graph.facebook.com/me?fields=email&access_token=" +
            url.QueryEscape(token.AccessToken)) 



 var respJSON map[string]interface{}
            err = json.NewDecoder(resp.Body).Decode(&respJSON)
            if err != nil {
                log.Println(err)
            }

现在 respJSON 将包含从 http.Get 请求返回的字段。就我而言,我通过 oauth 从 facebook 收到用户的电子邮件,所以我的 respJSON 地图将包含

respJSON["email"] // would yield the user's email

然后我创建了一个用户对象,并自己设置了电子邮件和其他字段。


推荐阅读