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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With