dongmoyu0336 2017-04-18 21:55
浏览 87
已采纳

如何使用从Google API收到的响应数据?

I'm trying to create login with google api authentication with oauth2. I'm getting response from google api (response.body) as:

{
 "id": "received ID",
 "email": "EMAIL",
 "verified_email": true,
 "name": "Name",
}

How can I access that data inside go program so that I can store it in database?

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "net/url"
    "strings"

    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "encoding/json"
)

var (
    oauthConf = &oauth2.Config{
        ClientID:     "CLIENTID",
        ClientSecret: "Secret",
        RedirectURL:  "http://localhost:8011/showprofile",
        //Scopes:       []string{"https://www.googleapis.com/auth/plus.login"},
        Scopes:[]string{"profile","email"},
        Endpoint:     google.Endpoint,
    }
    oauthStateString = "thisshouldberandom"
)

const htmlIndex = `<html><body>
Logged in with <a href="/login">facebook</a>
</body></html>
`

func handleMain(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    w.WriteHeader(http.StatusOK)
    w.Write([]byte(htmlIndex))
}

func handleGoogleLogin(w http.ResponseWriter, r *http.Request) {
    Url, err := url.Parse(oauthConf.Endpoint.AuthURL)
    if err != nil {
        log.Fatal("Parse: ", err)
    }
    parameters := url.Values{}
    parameters.Add("client_id", oauthConf.ClientID)
    parameters.Add("scope", strings.Join(oauthConf.Scopes, " "))
    parameters.Add("redirect_uri", oauthConf.RedirectURL)
    parameters.Add("response_type", "code")
    parameters.Add("state", oauthStateString)
    Url.RawQuery = parameters.Encode()
    url := Url.String()
    fmt.Println("URL" + url)
    http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
    fmt.Println("Call back working")
    state := r.FormValue("state")
    if state != oauthStateString {
        fmt.Printf("invalid oauth state, expected '%s', got '%s'
", oauthStateString, state)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }

    code := r.FormValue("code")

    token, err := oauthConf.Exchange(oauth2.NoContext, code)
    if err != nil {
        fmt.Printf("oauthConf.Exchange() failed with '%s'
", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }


    resp,err:=  http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken)

    if err != nil {
        fmt.Printf("Get: %s
", err)
        http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
        return
    }
    fmt.Println(resp.Body)
    defer resp.Body.Close()

    response, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("ReadAll: %s
", err)
        http.Redirect(w, r, "/showprofile", http.StatusTemporaryRedirect)
        return
    }



    log.Printf("parseResponseBody: %s
", string(response))

    http.Redirect(w, r, "/showprofile", http.StatusTemporaryRedirect)
}

func main() {
    http.HandleFunc("/", handleMain)
    http.HandleFunc("/login", handleGoogleLogin)
    http.HandleFunc("/showprofile", handleGoogleCallback)
    fmt.Print("Started running on http://localhost:8011
")
    log.Fatal(http.ListenAndServe(":8011", nil))
}
  • 写回答

1条回答 默认 最新

  • dongyanju1094 2017-04-18 23:12
    关注

    Fixed it by using json.Unmarshal.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图