Skip to content

Instantly share code, notes, and snippets.

@troy0820
Created February 27, 2019 19:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troy0820/1b18183df9103b0a1987786e25aab041 to your computer and use it in GitHub Desktop.
Save troy0820/1b18183df9103b0a1987786e25aab041 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"io"
"net/http"
"os"
)
//Create headers struct to inject into request
type headers struct {
rt http.RoundTripper //RoundTripper interface
v map[string]string
}
//satisfying the interface
func (h *headers) RoundTrip(r *http.Request) (*http.Response, error) {
for k, v := range h.v {
r.Header.Set(k, v)
}
return h.rt.RoundTrip(r)
//This will do whatever our RT interface type does so because we are using the Default transport
//we don't have to worry how that will be handled. If we used anything else, it passes it off to that type's RT interface type's function
//that satisfies it.
}
/*Default transport is going to call our RoundTrip function. Because our rt (interface type on struct) satisfies the RT interface
The default transport type will also satisfy the RT interface (that's why we are able to put it on our type that is a RT interface)
*/
func NewHeaderTransport() *headers {
return &headers{
rt: http.DefaultTransport,
v: map[string]string{"foo": "bar"},
}
}
func main() {
c := &http.Client{
Transport: &headers{ //using header struct because it satisfies the interface
rt: http.DefaultTransport, //using default transport to dynamic dispatch calls from our RoundTrip function
v: map[string]string{"foo": "bar"},
},
}
res, err := c.Get("http://icanhazip.com")
if err != nil {
fmt.Println(err.Error())
}
io.Copy(os.Stdout, res.Body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment