httpgologging

Logging All HTTP Request and Response from done through an HTTP Client


I have the following simple http.Client:

import (
 "net/http"
 "log"
)
...
func main() {
   ...
   link = "http://example.com"
   method = "GET"
   req, _ := http.NewRequest(method, link, nil)

   client := &http.Client{}

   myZapLogger.Info("Sending a %s request to %s\n", method, link)

   resp, err := client.Do(req)
   if err != nil {
      myZapLogger.Error(..., err) // I'm logging rather than fatal-ing or so
   } else { 
      myZapLogger.Info("Received a %d on request X", resp.StatusCode)
   }
   ...
}

...

I was looking for a way to do the above for each request through a hook (or so), so that it's triggered automatically each time. I can write a function the encloses all that, but in a case where I'm passing an http client to some other package, I wouldn't be able to control/log such requests that way (e.g. aws-go-sdk).

Is there a way to do this through contexts or attaching hooks to the client?

Thanks


Solution

  • eudore's comment answers the question; I'll just put it into code:

    type MyRoundTripper struct {}
    
    func (t MyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
        
        // Do work before the request is sent
    
        resp, err := http.DefaultTransport.RoundTrip(req)
        if err != nil {
            return resp, err
        }
        
        // Do work after the response is received
    
        return resp, err
    }
    

    To use it, you'll just pass it to your HTTP Client:

    rt := MyRoundTripper{}
    client := http.Client{Transport: rt}