SoFunction
Updated on 2025-03-04

Detailed explanation of the RoundTripper interface in the Golang net/http package

What is RoundTripper?

RoundTripper is an interface in the net/http package. It defines methods for handling HTTP request return and response, and is the core part of executing http requests in the structure. The interface is defined as follows:

type RoundTripper interface {
	RoundTrip(*Request) (*Response, error)
}

Only a RoundTrip method is defined to perform a single HTTP transaction, send request data, and return the corresponding response data. RoundTrip should not parse response data, especially if the response data is obtained, RoundTrip must return an error with nil (regardless of the HTTP status code of the response). If no ring data is obtained, a non-nil error should be returned, and RoundTrip should not attempt to handle more advanced protocol details such as redirection, authentication, or cookies.

Apart from consuming and closing requested Body, RoundTrip should not modify the request, and RoundTrip can read requested fields in a separate goroutine. The caller should not change or reuse the request until the Response Body is closed. RoundTrip must always close the body (even if an error is encountered), but according to implementation, it can be closed in a separate goroutine even after RoundTrip returns.

Use scenarios

With the help of RoundTripper, you can add a specific header to each request or perform specific processing on the returned response data, such as recording a log or executing corresponding logic based on the returned status code. Next, let’s look at a link tracking function. You only need to implement the RoundTripper interface. While executing HTTP requests, you collect telemetry data, such as the duration of the request, status code, etc., which can be used for performance monitoring and troubleshooting. The example code for implementing the RoundTripper interface is as follows:

package http_otel
import (
	"net/http"
	"/otel"
	"/otel/attribute"
	"/otel/codes"
)
type OtelRoundTripper struct {
	original 
}
func (ort *OtelRoundTripper) RoundTrip(req *) (*, error) {
	tracer := ("")
	ctx, span := ((), )
	defer ()
	req = (ctx)
	resp, err := (req)
	if err != nil {
		(err)
		(, ())
	} else {
		attrs := []{
			{
				Key:   "http.status_code",
				Value: (),
			},
			{
				Key:   "",
				Value: (),
			},
			{
				Key:   "",
				Value: (()),
			},
			{
				Key:   "",
				Value: (),
			},
			{
				Key:   "http.user_agent",
				Value: (()),
			},
		}
		(attrs...)
	}
	return resp, err
}
func New() *OtelRoundTripper {
	return &OtelRoundTripper{
		original: tripper,
	}
}

The link tracking code is implemented using the net/http package as follows:

package main
import (
    "bytes"
    "fmt"
    "xxx/http-otel"
    "io"
    "net/http"
)
func main() {
    reader := ([]byte(`{"foo":"bar"}`))
    request, err := ("POST", "/user/list", reader)
    if err != nil {
       panic(err)
    }
    request = (traceCtx) // traceCtx refers to the context above, here is used as a demonstration    ("Content-Type", "application/json")
    client := {Transport: http_otel.New()}
    resp, err := (request)
    if err != nil {
       panic(err)
    }
    defer ()
    b, err := ()
    (string(b), err)
}

First, an OtelRoundTripper structure is defined for implementing link tracking functions, and then the RoundTrip method is implemented. In the RoundTrip method, a new trace span is first opened and the trace information is encoded into the header of the HTTP request. After the request is completed, the returned HTTP response information is recorded in the trace and the HTTP response data is returned.

summary

The power of the RoundTripper interface is the ability to customize and control the processing of HTTP requests in a simple and extensible way. Whether adding a specific header, processing responses, or executing other more advanced logic, it can be achieved with the help of RoundTripper.

The above is a detailed explanation of the RoundTripper interface in the Golang net/http package. For more information about the Golang RoundTripper interface, please follow my other related articles!