TIL: net/http/httptrace

I write a few lines of Go here and there every few months, therefore I am basically a hobbyist (even though serious work with Kubernetes demands more of it). Today a friend had a very valid question:

How can I know the source port of my HTTP request when using net/http?

Pavlos

This is a valid question. If I have a socket, I should know all four aspects of it (src IP, src port, dst IP, dst port) and protocol of course. But it turns out this is not quite possible with net/http and another friend suggested making your custom transport to have control over such unexported information.

I had a flash and I thought “It can’t be such that no-one has written something that traces an HTTP connection in Go!”. It turns I was right and net/http/httptrace is right there and you can get the information needed thanks to the net.Conn struct (pardon the missing error handling):

package main

import (
    "fmt"
    "net/http"
    "net/http/httptrace"
    "io/ioutil"
)

func main() {
    client := http.Client{}
    req, _ := http.NewRequest("GET", "https://jsonip.com", nil)
        
    trace := &httptrace.ClientTrace{
        GotConn: func(connInfo httptrace.GotConnInfo) {
            fmt.Printf("GotConn: %v %v\n", connInfo.Conn.LocalAddr(), connInfo.Conn.RemoteAddr())
        },
    }
  
    req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
    res, _ := client.Do(req)
    resBody, _ := ioutil.ReadAll(res.Body)
    fmt.Printf("%s\n", resBody)
}

I get that this can be written in a better manner, but for now I am happy that I learned something new.

Leave a comment