Created
December 27, 2018 23:49
-
-
Save Adron/f418d8e745fe1cf269499728538c10f0 to your computer and use it in GitHub Desktop.
Get Bearer Token Function for go-twitter
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
func getBearerToken(consumerKey, consumerSecret string) (string, error) { | |
req, err := http.NewRequest("POST", "https://api.twitter.com/oauth2/token", | |
strings.NewReader("grant_type=client_credentials")) | |
if err != nil { | |
return "", fmt.Errorf("cannot create /token request: %+v", err) | |
} | |
b64Token := base64.StdEncoding.EncodeToString( | |
[]byte(fmt.Sprintf("%s:%s", consumerKey, consumerSecret))) | |
req.Header.Add("Authorization", "Basic "+b64Token) | |
req.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8") | |
resp, err := http.DefaultClient.Do(req) | |
if err != nil { | |
return "", fmt.Errorf("/token request failed: %+v", err) | |
} | |
defer resp.Body.Close() | |
var v struct { | |
AccessToken string `json:"access_token"` | |
} | |
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil { | |
return "", fmt.Errorf("error parsing json in /token response: %+v", err) | |
} | |
if v.AccessToken == "" { | |
return "", fmt.Errorf("/token response does not have access_token") | |
} | |
return v.AccessToken, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment