Golang: Tracking Server Process Time to add Server-Timing in HTTP Header

Kecci
2 min readJan 31, 2021

In performance scenario, as client, they want to know how long process time form the server. So the server should have tracker to show server process time information.

There are several information, such as database read, application process, cache read, file read, total duration. Read more HTTP Server-Timing: https://www.w3.org/TR/server-timing/

What I’m doing now, I was looking from echo framework to show server-time, but I there is no feature middleware to record server-time.

Finally, I found this library called mitchellh/go-server-timing . It is simple and lightweight use to record and tracking metric of Server-Timing.

mitchellh/go-server-timing is Go (golang) library for creating and consuming HTTP Server-Timing headers

Example Header Server-Time

EXAMPLE 1> GET /resource HTTP/1.1
> Host: example.com


< HTTP/1.1 200 OK
< Server-Timing: miss, db;dur=53, app;dur=47.2
< Server-Timing: customView, dc;desc=atl
< Server-Timing: cache;desc="Cache Read";dur=23.2
< Trailer: Server-Timing
< (... snip response body ...)
< Server-Timing: total;dur=123.4

mitchellh/go-server-timing

Installation

$ go get github.com/mitchellh/go-server-timing

Usage

I show you this example of using controller with echo web framwork. But you can change by native http/net or another library.

package controllerimport (
"fmt"
"github.com/labstack/echo/v4"
servertiming "github.com/mitchellh/go-server-timing"
)
func Hello(ctx echo.Context) error {
timing := servertiming.FromContext(ctx.Request().Context())
metric := timing.NewMetric("hello-show").WithDesc("Show Hello").Start()
hello := "Hello"
fmt.Println(hello)
metric.Stop()
ctx.Response().Header().Add(servertiming.HeaderKey, metric.String())
return c.String(http.StatusOK, hello)
}

Conclusion

  • Concurrency-safe structures for easily recording timings of multiple concurrency tasks.
  • Parse Server-Timing headers as a client.
  • Note: No browser properly supports sending the Server-Timing header as an HTTP Trailer so the Middleware only supports a normal header currently.
  • Either Chrome 65 or higher or Firefox 71 or higher is required to properly display server timings in the devtools.
  • IE, Opera, and others are unknown at this time.

Source

--

--