【问题标题】:I want know Gin Framwork function, which is similar to http.Get and http.Post我想知道Gin Framwork函数,类似于http.Get和http.Post
【发布时间】:2021-11-22 06:02:46
【问题描述】:

在开发 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

我想要 gin framework 方法,如果你提出任何想法,我将不胜感激

【问题讨论】:

  • Gin 是服务器库,而不是客户端库。只需使用 encoding/json 解组数据。
  • 谢谢!!我用过 json.Unmarshal 我可以处理它

标签: go oauth-2.0 oauth bind


【解决方案1】:

我遇到了同样的问题,我找不到任何 gin 的内部功能来满足它(也许我的研究不完整)。但这是我的处理方式。 您可以使用带有 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多