Add caching to web assets (#22137)

This commit is contained in:
Ryan Clark 2023-02-23 12:20:58 +00:00 committed by GitHub
parent 2a2f4c9f44
commit 15bd28ae82
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 1 deletions

View file

@ -22,6 +22,7 @@ import (
"fmt"
"net/http"
"strings"
"time"
)
// SetNoCacheHeaders tells proxies and browsers do not cache the content
@ -31,6 +32,11 @@ func SetNoCacheHeaders(h http.Header) {
h.Set("Expires", "0")
}
// SetCacheHeaders tells proxies and browsers to cache the content
func SetCacheHeaders(h http.Header, maxAge time.Duration) {
h.Set("Cache-Control", fmt.Sprintf("max-age=%.f, immutable", maxAge.Seconds()))
}
// SetDefaultSecurityHeaders adds headers that should generally be considered safe defaults. It is expected that all
// responses should be able to add these headers without negative impact.
func SetDefaultSecurityHeaders(h http.Header) {

View file

@ -402,7 +402,12 @@ func NewHandler(cfg Config, opts ...HandlerOption) (*APIHandler, error) {
// serve Web UI:
if strings.HasPrefix(r.URL.Path, "/web/app") {
http.StripPrefix("/web", makeGzipHandler(http.FileServer(cfg.StaticFS))).ServeHTTP(w, r)
fs := http.FileServer(cfg.StaticFS)
fs = makeGzipHandler(fs)
fs = makeCacheHandler(fs)
http.StripPrefix("/web", fs).ServeHTTP(w, r)
} else if strings.HasPrefix(r.URL.Path, "/web/") || r.URL.Path == "/web" {
csrfToken, err := csrf.AddCSRFProtection(w, r)
if err != nil {

33
lib/web/cachehandler.go Normal file
View file

@ -0,0 +1,33 @@
/*
Copyright 2023 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package web
import (
"net/http"
"time"
"github.com/gravitational/teleport/lib/httplib"
)
// makeCacheHandler adds support for gzip compression for given handler.
func makeCacheHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
httplib.SetCacheHeaders(w.Header(), time.Hour*24*365 /* one year */)
handler.ServeHTTP(w, r)
})
}