39 lines
937 B
Go
39 lines
937 B
Go
|
|
package httpClient
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"net/http"
|
||
|
|
)
|
||
|
|
|
||
|
|
type AuthTransport struct {
|
||
|
|
Token string
|
||
|
|
}
|
||
|
|
|
||
|
|
type CustomClient struct {
|
||
|
|
client *http.Client
|
||
|
|
}
|
||
|
|
|
||
|
|
// RoundTrip transport method implementation with jwt in header
|
||
|
|
func (t *AuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||
|
|
req.Header.Add("Authorization", fmt.Sprintf("Beare%s", t.Token))
|
||
|
|
return http.DefaultTransport.RoundTrip(req)
|
||
|
|
}
|
||
|
|
|
||
|
|
// GetHttpClient Returns httpClient with jwt in headers
|
||
|
|
func getHttpClient(token string) *http.Client {
|
||
|
|
return &http.Client{Transport: &AuthTransport{Token: token}}
|
||
|
|
}
|
||
|
|
|
||
|
|
// GetHttpClient Returns CustomClient with jwt in headers
|
||
|
|
func GetHttpClient(token string) *CustomClient {
|
||
|
|
return &CustomClient{getHttpClient(token)}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (client CustomClient) Do(req *http.Request) (*http.Response, error) {
|
||
|
|
resp, err := client.client.Do(req)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("error sending request: %w", err)
|
||
|
|
}
|
||
|
|
return resp, nil
|
||
|
|
}
|