import ( "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/calendar/v3" ) // Set up the OAuth2 config config := &oauth2.Config{ ClientID: "your-client-id", ClientSecret: "your-client-secret", RedirectURL: "http://localhost:8080/oauth2callback", Scopes: []string{ "https://www.googleapis.com/auth/calendar", }, Endpoint: google.Endpoint, } // Get the URL to redirect the user to for authorization url := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) // After the user authorizes, get the access token // (using the code that was passed as a query parameter) token, err := config.Exchange(ctx, code) if err != nil { log.Fatalf("Unable to retrieve token from web %v", err) } // Use the access token to make API requests srv, err := calendar.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token))) if err != nil { log.Fatalf("Unable to create calendar Service %v", err) } // Now you can make API requests with the srv client events, err := srv.Events.List("primary").Do()
import ( "golang.org/x/oauth2" "golang.org/x/oauth2/github" "github.com/google/go-github/github" ) // Set up the OAuth2 config config := &oauth2.Config{ ClientID: "your-client-id", ClientSecret: "your-client-secret", RedirectURL: "http://localhost:8080/oauth2callback", Scopes: []string{ "user", "repo", }, Endpoint: github.Endpoint, } // Get the URL to redirect the user to for authorization url := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) // After the user authorizes, get the access token // (using the code that was passed as a query parameter) token, err := config.Exchange(ctx, code) if err != nil { log.Fatalf("Unable to retrieve token from web %v", err) } // Use the access token to create a client for making API requests // (using the go-github library) ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token.AccessToken}) tc := oauth2.NewClient(ctx, ts) client := github.NewClient(tc) // Now you can make API requests with the client user, _, err := client.Users.Get(ctx, "")This example shows how to use the golang.org/x/oauth2/config package to authorize access to GitHub APIs. The `config` object is created with the necessary client ID, client secret, and authorization scopes. The `AuthCodeURL` method is used to get the URL to redirect the user to for authorization. After the user authorizes and is redirected back to the application, the `Exchange` method is used to exchange the authorization code for an access token. The `StaticTokenSource` and `NewClient` methods are used to create a client for making API requests, using the access token as the authentication method. This example uses the `go-github` library for making GitHub API requests.