How can I use data received as response from google api?

huangapple go评论77阅读模式
英文:

How can I use data received as response from google api?

问题

我正在尝试使用OAuth2和Google API身份验证创建使用Google API身份验证的登录功能。我从Google API收到的响应(response.body)如下所示:

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

我想知道如何在Go程序中访问这些数据,以便我可以将其存储在数据库中。

以下是你提供的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{"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))
}

请问有什么我可以帮助你的吗?

英文:

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

{
&quot;id&quot;: &quot;received ID&quot;,
&quot;email&quot;: &quot;EMAIL&quot;,
&quot;verified_email&quot;: true,
&quot;name&quot;: &quot;Name&quot;,
}

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

package main
import (
&quot;fmt&quot;
&quot;io/ioutil&quot;
&quot;log&quot;
&quot;net/http&quot;
&quot;net/url&quot;
&quot;strings&quot;
&quot;golang.org/x/oauth2&quot;
&quot;golang.org/x/oauth2/google&quot;
&quot;encoding/json&quot;
)
var (
oauthConf = &amp;oauth2.Config{
ClientID:     &quot;CLIENTID&quot;,
ClientSecret: &quot;Secret&quot;,
RedirectURL:  &quot;http://localhost:8011/showprofile&quot;,
//Scopes:       []string{&quot;https://www.googleapis.com/auth/plus.login&quot;},
Scopes:[]string{&quot;profile&quot;,&quot;email&quot;},
Endpoint:     google.Endpoint,
}
oauthStateString = &quot;thisshouldberandom&quot;
)
const htmlIndex = `&lt;html&gt;&lt;body&gt;
Logged in with &lt;a href=&quot;/login&quot;&gt;facebook&lt;/a&gt;
&lt;/body&gt;&lt;/html&gt;
`
func handleMain(w http.ResponseWriter, r *http.Request) {
w.Header().Set(&quot;Content-Type&quot;, &quot;text/html; charset=utf-8&quot;)
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(&quot;Parse: &quot;, err)
}
parameters := url.Values{}
parameters.Add(&quot;client_id&quot;, oauthConf.ClientID)
parameters.Add(&quot;scope&quot;, strings.Join(oauthConf.Scopes, &quot; &quot;))
parameters.Add(&quot;redirect_uri&quot;, oauthConf.RedirectURL)
parameters.Add(&quot;response_type&quot;, &quot;code&quot;)
parameters.Add(&quot;state&quot;, oauthStateString)
Url.RawQuery = parameters.Encode()
url := Url.String()
fmt.Println(&quot;URL&quot; + url)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleGoogleCallback(w http.ResponseWriter, r *http.Request) {
fmt.Println(&quot;Call back working&quot;)
state := r.FormValue(&quot;state&quot;)
if state != oauthStateString {
fmt.Printf(&quot;invalid oauth state, expected &#39;%s&#39;, got &#39;%s&#39;\n&quot;, oauthStateString, state)
http.Redirect(w, r, &quot;/&quot;, http.StatusTemporaryRedirect)
return
}
code := r.FormValue(&quot;code&quot;)
token, err := oauthConf.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf(&quot;oauthConf.Exchange() failed with &#39;%s&#39;\n&quot;, err)
http.Redirect(w, r, &quot;/&quot;, http.StatusTemporaryRedirect)
return
}
resp,err:=  http.Get(&quot;https://www.googleapis.com/oauth2/v2/userinfo?access_token=&quot; + token.AccessToken)
if err != nil {
fmt.Printf(&quot;Get: %s\n&quot;, err)
http.Redirect(w, r, &quot;/&quot;, http.StatusTemporaryRedirect)
return
}
fmt.Println(resp.Body)
defer resp.Body.Close()
response, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf(&quot;ReadAll: %s\n&quot;, err)
http.Redirect(w, r, &quot;/showprofile&quot;, http.StatusTemporaryRedirect)
return
}
log.Printf(&quot;parseResponseBody: %s\n&quot;, string(response))
http.Redirect(w, r, &quot;/showprofile&quot;, http.StatusTemporaryRedirect)
}
func main() {
http.HandleFunc(&quot;/&quot;, handleMain)
http.HandleFunc(&quot;/login&quot;, handleGoogleLogin)
http.HandleFunc(&quot;/showprofile&quot;, handleGoogleCallback)
fmt.Print(&quot;Started running on http://localhost:8011\n&quot;)
log.Fatal(http.ListenAndServe(&quot;:8011&quot;, nil))
}

答案1

得分: 1

通过使用json.Unmarshal进行修复。

英文:

Fixed it by using json.Unmarshal.

huangapple
  • 本文由 发表于 2017年4月19日 05:55:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/43482864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定