Skip to content

Instantly share code, notes, and snippets.

@icyflame
Created December 15, 2017 04:33
Show Gist options
  • Save icyflame/08d0d114fbc08b7948164f3214b83f82 to your computer and use it in GitHub Desktop.
Save icyflame/08d0d114fbc08b7948164f3214b83f82 to your computer and use it in GitHub Desktop.
Get app authentication access token for the Twitter API in Golang
package main
import b64 "encoding/base64"
import "encoding/json"
type BearerToken struct {
Token_Type string
Access_Token string
}
func main() {
var tok BearerToken
req, err := http.NewRequest("POST", "https://api.twitter.com/oauth2/token", strings.NewReader("grant_type=client_credentials"))
if err != nil {
log.Fatal(err)
} else {
data := os.Getenv("CONSUMER_KEY") + ":" + os.Getenv("CONSUMER_SECRET")
b64_token := b64.StdEncoding.EncodeToString([]byte(data))
// log.Printf("%s", b64_token)
req.Header.Add("Authorization", "Basic " + b64_token)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
access_tok_client := &http.Client{}
resp, err := access_tok_client.Do(req)
if err != nil {
log.Fatal(err)
} else {
bearer, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
} else {
err := json.Unmarshal(bearer, &tok)
if err != nil {
log.Fatal(err)
} else {
log.Printf("%s", tok.Access_Token)
}
}
}
}
log.Printf("Access token: %s", tok.Access_Token);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment