Created
November 3, 2019 23:44
-
-
Save bunker-inspector/1a858288f72b99d9ecd186277fa3fe5b to your computer and use it in GitHub Desktop.
Simple Twitter API Auth
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 twitter | |
import ( | |
"github.com/BurntSushi/toml" | |
"os" | |
"fmt" | |
"sync" | |
"bufio" | |
"net/http" | |
"io/ioutil" | |
"encoding/base64" | |
"encoding/json" | |
"strings" | |
) | |
const BASE = "https://api.twitter.com" | |
const STREAM = "https://stream.twitter.com/1.1" | |
var setBearerTokenOnce sync.Once | |
var bearerToken string | |
type BearerTokenData struct { | |
Token string `json:"access_token"` | |
Type string `json:"token_type"` | |
} | |
type Client struct { | |
ConsumerKey string `toml:consumerKey` | |
ConsumerSecret string `toml:consumerSecret` | |
AccessToken string `toml:accessToken` | |
AccessSecret string `toml:accessSecret` | |
Http *http.Client | |
} | |
func setBearerToken(c* Client) { | |
unencodedCreds := fmt.Sprintf("%s:%s", c.ConsumerKey, c.ConsumerSecret) | |
encodedCreds := base64.StdEncoding.EncodeToString([]byte(unencodedCreds)) | |
requestBody := strings.NewReader("grant_type=client_credentials") | |
req, _ := http.NewRequest("POST", fmt.Sprintf("%s/oauth2/token", BASE), requestBody) | |
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", encodedCreds)) | |
req.Header.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8") | |
resp, _ := c.Http.Do(req) | |
body, _ := ioutil.ReadAll(resp.Body) | |
tokenData := BearerTokenData{} | |
err := json.Unmarshal(body, &tokenData) | |
if err != nil { | |
fmt.Println("Error unmarshaling access token response") | |
} | |
fmt.Println(tokenData.Token) | |
bearerToken = fmt.Sprintf("Bearer %s", tokenData.Token) | |
} | |
func NewClient() *Client { | |
var client Client | |
path := fmt.Sprintf("%s/config/twitter.toml", os.Getenv("GOPATH")) | |
if _, err := toml.DecodeFile(path, &client); err != nil { | |
panic(err.Error()) | |
} | |
client.Http = &http.Client{} | |
setBearerTokenOnce.Do(func() {setBearerToken(&client)}) | |
return &client | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment