登录
首页 >  Golang >  Go问答

了解Gin Framework:与http.Get和http.Post类似的功能

来源:stackoverflow

时间:2024-02-17 11:15:25 452浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《了解Gin Framework:与http.Get和http.Post类似的功能》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

在开发oauth授权时,我遇到了binding问题

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的数据类型 我无法绑定令牌结构

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


正确答案


我遇到了同样的问题,并且我找不到任何 gin 的内部功能来满足它(也许我的研究不完整)。但这是我的处理方式。 您可以将 map[string]interface{} 与 json.newdecoder 一起使用 获得一个想法:

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

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

以上就是《了解Gin Framework:与http.Get和http.Post类似的功能》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>