Skip to content

Instantly share code, notes, and snippets.

@sergeyklay
Last active February 19, 2024 07:52
Show Gist options
  • Save sergeyklay/9f51bcd6905788382b5deb790c68eac1 to your computer and use it in GitHub Desktop.
Save sergeyklay/9f51bcd6905788382b5deb790c68eac1 to your computer and use it in GitHub Desktop.
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}
}
@dv-blk
Copy link

dv-blk commented Nov 27, 2019

Was looking all over for this!

@sergeyklay
Copy link
Author

@dv-blk You're welcome :)

@josephscottstevens
Copy link

Very helpful snippet, thank you so much! :) I did notice a small typo in the print line for error handling "endpoind".

@sergeyklay
Copy link
Author

@josephscottstevens

Very helpful snippet, thank you so much! :) I did notice a small typo in the print line for error handling "endpoind".

Thank you for the bug report. Fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment