Is there 'middleware' for Go http client?

You can use the Transport parameter in HTTP client to that effect, with a composition pattern, using the fact that:

  • http.Client.Transport defines the function that will handle all HTTP requests;
  • http.Client.Transport has interface type http.RoundTripper, and can thus be replaced with your own implementation;

For example:

package main

import (
    "fmt"
    "net/http"
)

// This type implements the http.RoundTripper interface
type LoggingRoundTripper struct {
    Proxied http.RoundTripper
}

func (lrt LoggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) {
    // Do "before sending requests" actions here.
    fmt.Printf("Sending request to %v\n", req.URL)

    // Send the request, get the response (or the error)
    res, e = lrt.Proxied.RoundTrip(req)

    // Handle the result.
    if (e != nil) {
        fmt.Printf("Error: %v", e)
    } else {
        fmt.Printf("Received %v response\n", res.Status)
    }

    return
}

func main() {
    httpClient := &http.Client{
        Transport: LoggingRoundTripper{http.DefaultTransport},
    }
    httpClient.Get("https://example.com/")
}

Feel free to alter names as you wish, I did not think on them for very long.

Tags:

Go