roundTripperFunc adapts an ordinary function or closure into an implementation of http.RoundTripper. It declares the RoundTrip-compatible function signature and adds a RoundTrip method that calls the function receiver, allowing Go to recognize the interface implementation implicitly. section 7.5.1
Listing 7.6 Satisfying RoundTripper (hit/hit_test.go)
package hit
import "net/http"
// roundTripperFunc is an adapter to allow the use of ordinary
// functions as an [http.RoundTripper]. If the receiver f is a
// function with the appropriate signature, roundTripperFunc(f)
// is an [http.RoundTripper] that calls the receiver.
type roundTripperFunc func( #1
*http.Request, #1
) (*http.Response, error) #1
func (f roundTripperFunc) RoundTrip( #2
r *http.Request, #2
) (*http.Response, error) { #2
return f(r) #3
}
Defines the adapter type and its forwarding RoundTrip method. section 7.5.1
Install an adapter as an HTTP transport
Convert a matching closure with roundTripperFunc, then assign it to an http.Client's Transport field. Client requests pass through the closure and receive its response. section 7.5.1
Test without an HTTP server
Create a fake function that returns an HTTP 500 response, convert it to roundTripperFunc, and use it as the client's Transport. Send can then be tested against a precise response. section 7.5.2
Listing 7.7 Testing with a fake RoundTripper (hit/hit_test.go)
package hit
import (
"net/http"
"testing"
)
. . .
func TestSendStatusCode(t *testing.T) {
t.Parallel()
req, err := http.NewRequest(http.MethodGet, "/", http.NoBody)
if err != nil {
t.Fatalf("creating http request: %v", err)
}
fake := func(_ *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusInternalServerError,
}, nil
}
client := &http.Client{
Transport: roundTripperFunc(fake),
}
result := Send(client, req)
if result.Status != http.StatusInternalServerError {
t.Errorf(
"got %d, want %d",
result.Status, http.StatusInternalServerError,
)
}
}
Shows a complete status-code test using a fake RoundTripper and a custom http.Client. section 7.5.2
