Application 2023-08-22

About Go's http.RoundTripper

Learn what Go http.RoundTripper interface is and how to use it as HTTP client middleware. Includes a custom RoundTripper for request logging and response latency measurement.

Read in: ja
About Go's http.RoundTripper

Overview

Writing about Go's http.RoundTripper.

What is http.RoundTripper?

An interface responsible for HTTP client communication.

cf. pkg.go.dev - net/http#RoundTripper

It allows customization of the process from sending a request to receiving a response in an HTTP client.

Think of it as middleware for the HTTP client.

Implementation Example

The source code is also available on github.com.

You can customize by implementing the RoundTripper interface and passing it to http.Client.

package main

import (
	"fmt"
	"net/http"
	"time"
)

// CustomRoundTripper is a custom implementation of http.RoundTripper
type CustomRoundTripper struct {
	Transport http.RoundTripper
}

func (c *CustomRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	start := time.Now()

	fmt.Printf("Requesting %s %s\n", req.Method, req.URL)

	resp, err := c.Transport.RoundTrip(req)

	elapsed := time.Since(start)
	fmt.Printf("Received response in %v\n", elapsed)

	return resp, err
}

func main() {
	client := &http.Client{
		Transport: &CustomRoundTripper{
			Transport: http.DefaultTransport,
		},
	}

	resp, err := client.Get("https://www.example.com")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	fmt.Println("Status Code:", resp.Status)
}
$ go run main.go
Requesting GET https://www.example.com
Received response in 530.885709ms
Status Code: 200 OK

Where to Use?

Use it when you want to insert some middleware-like processing on the HTTP client side.

It seems useful when you want to set up uniform processing in an HTTP client.

When you want to insert processing for specific endpoints, it might be more flexible to prepare your own middleware.

References

Tags: Golang
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles