Created
August 7, 2019 08:34
[go] BearerAuthClient
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 test_helper | |
import ( | |
"fmt" | |
"io" | |
"net/http" | |
) | |
type BearerAuthClient struct { | |
token string | |
client *http.Client | |
} | |
func NewBearerAuthClient(token string) *BearerAuthClient { | |
client := new(http.Client) | |
return &BearerAuthClient{ | |
token, client, | |
} | |
} | |
func (c *BearerAuthClient) newRequest(method, url string, body io.Reader) (*http.Request, error) { | |
req, err := http.NewRequest(method, url, body) | |
if err != nil { | |
return nil, err | |
} | |
req.Header.Add("Authorization", fmt.Sprintf("Bearer %v", c.token)) | |
return req, err | |
} | |
func (c *BearerAuthClient) Request(method, url string, body io.Reader) (*http.Response, error) { | |
req, err := c.newRequest(method, url, body) | |
if err != nil { | |
return nil, err | |
} | |
return c.client.Do(req) | |
} | |
func (c *BearerAuthClient) Get(url string) (*http.Response, error) { | |
req, err := c.newRequest("GET", url, nil) | |
if err != nil { | |
return nil, err | |
} | |
return c.client.Do(req) | |
} | |
func (c *BearerAuthClient) Post(url string, contentType string, body io.Reader) (*http.Response, error) { | |
req, err := c.newRequest("POST", url, body) | |
if err != nil { | |
return nil, err | |
} | |
req.Header.Add("Content-Type", contentType) | |
return c.client.Do(req) | |
} | |
func (c *BearerAuthClient) Put(url string, contentType string, body io.Reader) (*http.Response, error) { | |
req, err := c.newRequest("PUT", url, body) | |
if err != nil { | |
return nil, err | |
} | |
req.Header.Add("Content-Type", contentType) | |
return c.client.Do(req) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment