README.md

etag #

ETag middleware for Go, built on net/http.

Because it is a plain func(http.Handler) http.Handler, it works with the standard library as well as any framework built on net/http (Echo, Gin, Chi, etc.).

Install #

go get tangled.org/akimo.dev/etag

Usage #

Wrap an http.Handler with NewMiddleware:

package main

import (
	"net/http"

	"tangled.org/akimo.dev/etag"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
		w.Write([]byte("hello"))
	})

	handler := etag.NewMiddleware()(mux)

	http.ListenAndServe(":8080", handler)
}

Echo #

Use echo.WrapMiddleware to adapt the net/http middleware:

e := echo.New()
e.Use(echo.WrapMiddleware(etag.NewMiddleware()))

Gin #

Gin has no built-in adapter for net/http middleware (gin.WrapH / gin.WrapF only wrap handlers, not middleware). Since gin.Engine implements http.Handler, wrap the whole router:

router := gin.Default()
router.GET("/", func(c *gin.Context) {
	c.String(http.StatusOK, "hello")
})

http.ListenAndServe(":8080", etag.NewMiddleware()(router))

The same pattern works for Chi and other net/http-based routers.

Configuration #

See godoc for available options.

What it does #

  • Buffers the response and attaches its hash as an ETag.
  • Automatically detects streaming responses, and skips buffering and ETag in that case.

What it does not do #

  • It does not return 304 / 412 for If-None-Match on methods other than GET / HEAD.
  • It does not implement If-Match handling.

These are left to the application, since the correct status code depends on your logic. Use WeakMatch / StrongMatch helpers for the comparison.

License #

BSD Zero Clause License