github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/web/middlewares/cache.go (about)

     1  package middlewares
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"time"
     7  )
     8  
     9  // CachingMiddleware sets "Cache-Control" and "ETag" headers
    10  func CachingMiddleware(h http.Handler, maxAge time.Duration, gitHash string) http.Handler {
    11  	cacheControl := fmt.Sprintf("private, max-age=%d", int64(maxAge.Seconds()))
    12  	etag := fmt.Sprintf(`"%s"`, gitHash)
    13  
    14  	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    15  		expTime := time.Now().Add(maxAge)
    16  
    17  		w.Header().Set("Expires", expTime.Format(http.TimeFormat))
    18  		w.Header().Set("Cache-Control", cacheControl)
    19  		w.Header().Set("ETag", etag)
    20  
    21  		h.ServeHTTP(w, r)
    22  	})
    23  }