Is there 'middleware' for Go http client?

Issue

I would like to ask if we can create ‘middleware’ functions for Go http client? Example I want to add a log function, so every sent request will be logged, or add setAuthToken so the token will be added to each request’s header.

Solution

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.

Answered By – Jean Hominal

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.