How do I call Google APIs with OAuth2 in Go?

Learn how to call Google APIs using OAuth2 authentication in Go. This guide provides a detailed example to help you integrate Google services into your applications effectively.
Google APIs, OAuth2, Go programming, integration, API calls, authentication

package main

import (
    "context"
    "fmt"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "net/http"
    "log"
    "io/ioutil"
)

func main() {
    ctx := context.Background()

    // Replace with your Google client ID and client secret
    config := &oauth2.Config{
        ClientID:     "YOUR_CLIENT_ID",
        ClientSecret: "YOUR_CLIENT_SECRET",
        RedirectURL:  "YOUR_REDIRECT_URL",
        Endpoint:     google.Endpoint,
        Scopes:       []string{"https://www.googleapis.com/auth/userinfo.profile"},
    }

    // Generate a URL to redirect user to authorize
    url := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
    fmt.Println("Visit the URL for the auth dialog:", url)

    // Once you get the authorization code, exchange it for an access token
    var code string
    fmt.Print("Enter the authorization code: ")
    fmt.Scan(&code)

    token, err := config.Exchange(ctx, code)
    if err != nil {
        log.Fatal(err)
    }

    client := config.Client(ctx, token)

    // Make a request to Google APIs with the authorized client
    resp, err := client.Get("https://www.googleapis.com/userinfo/v2/me")
    if err != nil {
        log.Fatal(err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Response from Google API:", string(body))
}
    

Google APIs OAuth2 Go programming integration API calls authentication