Skip to content

Instantly share code, notes, and snippets.

@koenbollen
Last active September 4, 2019 12:06
Show Gist options
  • Save koenbollen/6ac0fbc8a3f06a2878e278898a50641e to your computer and use it in GitHub Desktop.
Save koenbollen/6ac0fbc8a3f06a2878e278898a50641e to your computer and use it in GitHub Desktop.
Quick http client with header override for authentication.
package main
import (
"bytes"
"fmt"
"net/http"
"net/url"
)
type TestClient struct {
http.Client
base *url.URL
key string
}
func New(base, key string) *TestClient {
u, _ := url.Parse(base)
c := &TestClient{
base: u,
key: key,
}
c.Transport = c
return c
}
func (c *TestClient) Echo(msg string) string {
resp, err := c.Get("/anything?msg=" + msg)
if err != nil {
return err.Error()
}
defer resp.Body.Close()
buf := &bytes.Buffer{}
buf.ReadFrom(resp.Body)
return resp.Status + " " + buf.String()
}
func (c *TestClient) RoundTrip(req *http.Request) (*http.Response, error) {
req.URL = c.base.ResolveReference(req.URL)
req.Header.Set("Authorization", c.key)
return http.DefaultTransport.RoundTrip(req)
}
func main() {
c := New("https://httpbin.org", "secret")
fmt.Println(c.Echo("test"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment