This repository has been archived on 2022-05-25. You can view files and clone it, but cannot push or open issues or pull requests.
elon-eats-my-tweets/twitter/api.go

52 lines
1.0 KiB
Go

package twitter
import (
"encoding/json"
"fmt"
"net/http"
)
type User struct {
ID string
Name string
Username string
}
func NewAPIClient(httpclient *http.Client) *APIClient {
return &APIClient{httpclient}
}
type APIClient struct {
*http.Client
}
func (c *APIClient) GetMe() (*User, error) {
type oauthResponse struct {
Data struct {
ID string `json:"id"`
Name string `json:"name"`
Username string `json:"username"`
} `json:"data"`
}
resp, err := c.Get("https://api.twitter.com/2/users/me")
if err != nil {
return nil, fmt.Errorf("error fetching resource: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error fetching resource: status code %d", resp.StatusCode)
}
var oauthResp oauthResponse
if err = json.NewDecoder(resp.Body).Decode(&oauthResp); err != nil {
return nil, fmt.Errorf("error decoding resource: %v", err)
}
return &User{
ID: oauthResp.Data.ID,
Name: oauthResp.Data.Name,
Username: oauthResp.Data.Username,
}, nil
}