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 (
"go.fifitido.net/twitch/api"
"go.fifitido.net/twitch/auth"
)
func NewAPI(authClient *auth.Client) *api.API {
return api.NewDefault(authClient)
func NewAPI(clientId, clientSecret, redirectUri string) *api.API {
return api.NewDefault(clientId, clientSecret, redirectUri)
}

View File

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