github.com/rpdict/ponzu@v0.10.1-0.20190226054626-477f29d6bf5e/system/db/cache.go (about)

     1  package db
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  	"net/http"
     7  	"strings"
     8  	"time"
     9  )
    10  
    11  // CacheControl sets the default cache policy on static asset responses
    12  func CacheControl(next http.Handler) http.HandlerFunc {
    13  	return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
    14  		cacheDisabled := ConfigCache("cache_disabled").(bool)
    15  		if cacheDisabled {
    16  			res.Header().Add("Cache-Control", "no-cache")
    17  			next.ServeHTTP(res, req)
    18  		} else {
    19  			age := int64(ConfigCache("cache_max_age").(float64))
    20  			etag := ConfigCache("etag").(string)
    21  			if age == 0 {
    22  				age = DefaultMaxAge
    23  			}
    24  			policy := fmt.Sprintf("max-age=%d, public", age)
    25  			res.Header().Add("ETag", etag)
    26  			res.Header().Add("Cache-Control", policy)
    27  
    28  			if match := req.Header.Get("If-None-Match"); match != "" {
    29  				if strings.Contains(match, etag) {
    30  					res.WriteHeader(http.StatusNotModified)
    31  					return
    32  				}
    33  			}
    34  
    35  			next.ServeHTTP(res, req)
    36  		}
    37  	})
    38  }
    39  
    40  // NewEtag generates a new Etag for response caching
    41  func NewEtag() string {
    42  	now := fmt.Sprintf("%d", time.Now().Unix())
    43  	etag := base64.StdEncoding.EncodeToString([]byte(now))
    44  
    45  	return etag
    46  }
    47  
    48  // InvalidateCache sets a new Etag for http responses
    49  func InvalidateCache() error {
    50  	err := PutConfig("etag", NewEtag())
    51  	if err != nil {
    52  		return err
    53  	}
    54  
    55  	return nil
    56  }