Skip to content

Instantly share code, notes, and snippets.

@fionera
Created August 18, 2020 00:38
Show Gist options
  • Save fionera/5a53b89d6e13651f9a41be0bf549e759 to your computer and use it in GitHub Desktop.
Save fionera/5a53b89d6e13651f9a41be0bf549e759 to your computer and use it in GitHub Desktop.
Intercept a HTTP Call
package main
import (
"bytes"
"context"
"io"
"net"
"net/http"
"os"
"time"
)
func main() {
(&http.Client{Transport: &test{}}).Get("http://google.com")
}
type test struct {
}
type ConnWrapper struct {
c net.Conn
w io.Writer
}
func (c *ConnWrapper) Read(b []byte) (n int, err error) {
read, err := c.c.Read(b)
_, _ = io.Copy(os.Stdout, bytes.NewReader(b))
return read, err
}
func (c *ConnWrapper) Write(b []byte) (n int, err error) {
return c.w.Write(b)
}
func (c *ConnWrapper) Close() error {
return c.c.Close()
}
func (c *ConnWrapper) LocalAddr() net.Addr {
return c.c.LocalAddr()
}
func (c *ConnWrapper) RemoteAddr() net.Addr {
return c.c.RemoteAddr()
}
func (c *ConnWrapper) SetDeadline(t time.Time) error {
return c.c.SetDeadline(t)
}
func (c *ConnWrapper) SetReadDeadline(t time.Time) error {
return c.c.SetReadDeadline(t)
}
func (c *ConnWrapper) SetWriteDeadline(t time.Time) error {
return c.c.SetWriteDeadline(t)
}
func (t *test) RoundTrip(req *http.Request) (*http.Response, error) {
c := http.Client{
}
transport := http.DefaultTransport.(*http.Transport)
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
d := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}
conn, err := d.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
return &ConnWrapper{
c: conn,
w: io.MultiWriter(conn, os.Stdout),
}, nil
}
return c.Do(req)
}
var (
_ http.RoundTripper = (*test)(nil)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment