Home

Awesome

client-timing

Build Status codecov GoDoc Go Report Card

An HTTP client for go-server-timing middleware.

Features:

Install

go get -u github.com/posener/client-timing

Usage

  1. Add a *clienttiming.Timer to your server handler, or create it in the handler function itself.

  2. Wrap the http.Handler with servertiming.Middleware.

  3. In the handler function, having timer of type *clienttiming.Timer and req is the *http.Request:

    a. Create an *http.Client using timer.Client(req.Context())

    b. Or create an http.RoundTripper using timer.Transport(req.Context())

  4. Use option a or b directly or inject it to a library that accepts them, in your outgoing HTTP request from the handler.

  5. That is it! the timing header will appear in the response from the handler.

Example

Suppose we have an HTTP handler:

type handler struct {
	timer *clienttiming.Timer
}

Our usage of that handler will be:

func main() {
	h := &handler{
		timer: clienttiming.New(clienttiming.WithName("my-server")),
	}
	log.Fatal(http.ListenAndServe(":8080", servertiming.Middleware(h)))
}

Example for Client function:

func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Create an http client using the request context
	c := h.timer.Client(r.Context())

	// Perform HTTP requests, as many as you like
	resp, err := c.Get("https://golang.org/")

	...
}

Example for Transport function:

func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Instrument an http client with a timing transport
	c := &http.Client{
		Transport: h.timer.Transport(r.Context()),
	}

	// Perform HTTP requests, as many as you like
	resp, err := c.Get("https://golang.org/")

	...
}

Run the example

go run ./example/main.go