package etag import ( "fmt" "net/http" ) const weakPrefix = "W/" func NewMiddleware(opts ...Option) func(http.Handler) http.Handler { cfg := defaultConfig for _, opt := range opts { opt(&cfg) } return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rw := newResponseWriter(w, cfg.maxBufferSize) next.ServeHTTP(rw, r) if rw.passthrough { return } if !rw.wroteHeader && rw.buf.Len() == 0 { // Nothing was written. Leave the underlying ResponseWriter // uncommitted so that frameworks which write error responses // after the middleware returns (e.g., Echo via // echo.WrapMiddleware) can still write with the correct // status code. Future writes through rw are forwarded // directly to the underlying writer. rw.delegate = true return } if (rw.statusCode != http.StatusOK && rw.statusCode != http.StatusCreated) || cfg.skipper(r) { w.WriteHeader(rw.statusCode) _, _ = w.Write(rw.buf.Bytes()) return } // Allow handlers to set their own ETag header. etag := rw.Header().Get("ETag") if etag == "" { value := cfg.generator(rw.buf.Bytes()) etag = fmt.Sprintf(`"%s"`, value) if cfg.weak { etag = weakPrefix + etag } rw.Header().Set("ETag", etag) } ifNoneMatch := r.Header.Get("If-None-Match") // We must use weak comparison for If-None-Match // https://www.rfc-editor.org/info/rfc9110/#section-13.1.2 if (r.Method == http.MethodGet || r.Method == http.MethodHead) && WeakMatch(ifNoneMatch, etag) { rw.Header().Del("Content-Length") w.WriteHeader(http.StatusNotModified) return } else { w.WriteHeader(rw.statusCode) } if r.Method != http.MethodHead { _, _ = w.Write(rw.buf.Bytes()) } }) } }