Add custom transport to api client

This commit is contained in:
Evan Fiordeliso 2024-03-07 19:06:02 -05:00
parent f33aef6e4a
commit fc50a199ef
3 changed files with 32 additions and 13 deletions

5
api.go
View File

@ -2,9 +2,8 @@ package twitch
import ( import (
"go.fifitido.net/twitch/api" "go.fifitido.net/twitch/api"
"go.fifitido.net/twitch/auth"
) )
func NewAPI(authClient *auth.Client) *api.API { func NewAPI(clientId, clientSecret, redirectUri string) *api.API {
return api.NewDefault(authClient) return api.NewDefault(clientId, clientSecret, redirectUri)
} }

View File

@ -39,9 +39,9 @@ import (
const HelixBaseUrl = "https://api.twitch.tv/helix" const HelixBaseUrl = "https://api.twitch.tv/helix"
type API struct { type API struct {
client *http.Client client *http.Client
baseUrl *url.URL baseUrl *url.URL
authClient *auth.Client Auth *auth.Client
Ads *ads.Ads Ads *ads.Ads
Analytics *analytics.Analytics Analytics *analytics.Analytics
@ -75,9 +75,9 @@ type API struct {
func New(client *http.Client, baseUrl *url.URL, authClient *auth.Client) *API { func New(client *http.Client, baseUrl *url.URL, authClient *auth.Client) *API {
return &API{ return &API{
client: client, client: client,
baseUrl: baseUrl, baseUrl: baseUrl,
authClient: authClient, Auth: authClient,
Ads: ads.New(client, baseUrl), Ads: ads.New(client, baseUrl),
Analytics: analytics.New(client, baseUrl), Analytics: analytics.New(client, baseUrl),
@ -110,21 +110,26 @@ func New(client *http.Client, baseUrl *url.URL, authClient *auth.Client) *API {
} }
} }
func NewDefault(authClient *auth.Client) *API { func NewDefault(clientId, clientSecret, redirectUri string) *API {
client := &http.Client{} client := &http.Client{
Transport: &apiTransport{
clientId: clientId,
},
}
baseUrl, _ := url.Parse(HelixBaseUrl) baseUrl, _ := url.Parse(HelixBaseUrl)
authClient := auth.NewClient(clientId, clientSecret, redirectUri)
return New(client, baseUrl, authClient) return New(client, baseUrl, authClient)
} }
func (a *API) WithClient(client *http.Client) *API { func (a *API) WithClient(client *http.Client) *API {
return New(client, a.baseUrl, a.authClient) return New(client, a.baseUrl, a.Auth)
} }
func (a *API) WithAuthToken(token *auth.Token) *API { func (a *API) WithAuthToken(token *auth.Token) *API {
return a.WithClient(&http.Client{ return a.WithClient(&http.Client{
Transport: &oauth2.Transport{ Transport: &oauth2.Transport{
Source: a.authClient.TokenSource(token), Source: a.Auth.TokenSource(token),
Base: a.client.Transport, Base: a.client.Transport,
}, },
}) })

15
api/transport.go Normal file
View File

@ -0,0 +1,15 @@
package api
import "net/http"
type apiTransport struct {
clientId string
}
var _ http.RoundTripper = (*apiTransport)(nil)
// RoundTrip implements http.RoundTripper.
func (a *apiTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Add("Client-ID", a.clientId)
return http.DefaultTransport.RoundTrip(req)
}