Last active
February 19, 2024 07:52
-
-
Save sergeyklay/9f51bcd6905788382b5deb790c68eac1 to your computer and use it in GitHub Desktop.
Example usage of https://godoc.org/golang.org/x/oauth2/clientcredentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"golang.org/x/net/context" | |
cc "golang.org/x/oauth2/clientcredentials" | |
"io/ioutil" | |
"net/http" | |
"os" | |
) | |
type SpecialClient struct { | |
*http.Client | |
} | |
func main() { | |
client := NewClient( | |
os.Getenv("CLIENT_ID"), | |
os.Getenv("CLIENT_SECRET"), | |
) | |
// the client will update its token if it's expired | |
resp, err := client.Get("http://some.remote.resource/path/to/resource") | |
if err != nil { | |
panic(err) | |
} | |
body, _ := ioutil.ReadAll(resp.Body) | |
defer resp.Body.Close() | |
// If response code is 200 it was successful | |
if resp.StatusCode == 200 { | |
fmt.Println("The request was successful. Response below:") | |
fmt.Println(string(body)) | |
} else { | |
fmt.Println("Could not perform request to the endpoint. Response below:") | |
fmt.Println(string(body)) | |
} | |
} | |
func NewClient(cid, csec string) *SpecialClient { | |
// this should match whatever service has given you | |
// client credential access | |
config := &cc.Config{ | |
ClientID: cid, | |
ClientSecret: csec, | |
TokenURL: "http://some.remote.resource/token", | |
Scopes: []string{"scope:name"}, | |
} | |
// you can modify the client (for example ignoring bad certs or otherwise) | |
// by modifying the context | |
ctx := context.Background() | |
client := config.Client(ctx) | |
return &SpecialClient{client} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@josephscottstevens
Thank you for the bug report. Fixed