Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there 'middleware' for Go http client?

Tags:

go

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.

like image 773
quangpn88 Avatar asked Sep 16 '16 09:09

quangpn88


People also ask

What is Go middleware?

A middleware handler is simply an http. Handler that wraps another http. Handler to do some pre- and/or post-processing of the request. It's called "middleware" because it sits in the middle between the Go web server and the actual handler.

How do I use Go middleware?

To implement middleware in Go, you need to make sure you have a type that satisfies the http. Handler interface. Ordinarily, this means that you need to attach a method with the signature ServeHTTP(http. ResponseWriter, *http.

What is Go HTTP client?

Go is a language designed by Google for use in a modern internet environment. It comes with a highly capable standard library and a built-in HTTP client.


1 Answers

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.

like image 82
Jean Hominal Avatar answered Nov 02 '22 04:11

Jean Hominal