login by google api
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var (
googleOauthConfig = &oauth2.Config{
RedirectURL: "http://localhost:8080/callback",
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
},
Endpoint: google.Endpoint,
}
)
func main() {
http.HandleFunc("/", handleMain)
http.HandleFunc("/login", handleLogin)
http.HandleFunc("/callback", handleCallback)
fmt.Println("Server is running at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleMain(w http.ResponseWriter, r *http.Request) {
html := `<html><body><a href="/login">Login with Google</a></body></html>`
fmt.Fprint(w, html)
}
func handleLogin(w http.ResponseWriter, r *http.Request) {
url := googleOauthConfig.AuthCodeURL("state")
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
func handleCallback(w http.ResponseWriter, r *http.Request) {
code := r.FormValue("code")
token, err := googleOauthConfig.Exchange(context.Background(), code)
if err != nil {
http.Error(w, "Failed to exchange token", http.StatusInternalServerError)
return
}
client := googleOauthConfig.Client(context.Background(), token)
response, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")
if err != nil {
http.Error(w, "Failed to get user info", http.StatusInternalServerError)
return
}
defer response.Body.Close()
var userInfo map[string]interface{}
err = json.NewDecoder(response.Body).Decode(&userInfo)
if err != nil {
http.Error(w, "Failed to decode user info", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Logged in with Google! Email: %s\n", userInfo["email"])
}
Explanation:
- Import necessary packages like context
, encoding/json
, fmt
, log
, net/http
, and the Google OAuth package golang.org/x/oauth2
and golang.org/x/oauth2/google
.
- Create a googleOauthConfig
struct containing your Google OAuth credentials (ClientID
and ClientSecret
), RedirectURL
, and scopes for accessing user info.
- Implement main()
to set up HTTP routes and start the server on port 8080
.
- Define handlers for the main page (/
), login (/login
), and callback (/callback
) URLs.
- handleMain
displays a simple HTML page with a link to initiate the Google login process.
- handleLogin
initiates the OAuth2 flow by redirecting the user to Google's authentication page.
- handleCallback
handles the callback from Google after the user authorizes the app. It retrieves the authorization code, exchanges it for an access token, uses the token to obtain user information from Google's userinfo API, and displays the user's email upon successful login.