go - 如何使用从 google api 收到的响应数据?

标签 go

我正在尝试使用 oauth2 使用 google api 身份验证创建登录。 我收到来自 google api (response.body) 的响应:

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

如何在 go 程序中访问该数据,以便将其存储在数据库中?

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'\n", 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'\n", 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\n", 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\n", err)
        http.Redirect(w, r, "/showprofile", http.StatusTemporaryRedirect)
        return
    }



    log.Printf("parseResponseBody: %s\n", 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\n")
    log.Fatal(http.ListenAndServe(":8011", nil))
}

最佳答案

使用 json.Unmarshal 修复了它。

关于go - 如何使用从 google api 收到的响应数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482864/

相关文章:

go - 如何将我的资源拆分成多个文件

go - 什么是计算机科学术语中的 go lang http.Request Body?

session - gorilla / session : Session be managed (persist changes) between handlers?

go - 为什么 ProxyServer 无法在 chromedp GO 上运行

go - Websocket 在 Echo Framework 中向所有客户端发送消息

go - 如何通过登录将 session 数据存储在 chi 路由器上下文中

go - 如果Go中的字段是 "filtered"是什么意思?

go - gin-gonic 是否并行处理请求?

macos - Docker 容器内构建的 Golang 二进制文件,还是 Mach-O 可执行文件格式?

go - 如何创建具有不同签名的函数片段?