2018-06-11 13:13:19 +00:00
|
|
|
package file
|
2016-12-30 23:20:38 +00:00
|
|
|
|
2017-01-25 22:45:03 +00:00
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
2021-12-13 09:34:55 +00:00
|
|
|
|
|
|
|
"github.com/gorilla/handlers"
|
2017-01-25 22:45:03 +00:00
|
|
|
)
|
2016-12-30 23:20:38 +00:00
|
|
|
|
2018-06-11 13:13:19 +00:00
|
|
|
// Handler represents an HTTP API handler for managing static files.
|
|
|
|
type Handler struct {
|
2016-12-30 23:20:38 +00:00
|
|
|
http.Handler
|
2022-04-05 04:29:57 +00:00
|
|
|
wasInstanceDisabled func() bool
|
2016-12-30 23:20:38 +00:00
|
|
|
}
|
|
|
|
|
2018-06-11 13:13:19 +00:00
|
|
|
// NewHandler creates a handler to serve static files.
|
2022-04-05 04:29:57 +00:00
|
|
|
func NewHandler(assetPublicPath string, wasInstanceDisabled func() bool) *Handler {
|
2018-06-11 13:13:19 +00:00
|
|
|
h := &Handler{
|
2021-12-13 09:34:55 +00:00
|
|
|
Handler: handlers.CompressHandler(
|
|
|
|
http.FileServer(http.Dir(assetPublicPath)),
|
|
|
|
),
|
2022-04-05 04:29:57 +00:00
|
|
|
wasInstanceDisabled: wasInstanceDisabled,
|
2016-12-30 23:20:38 +00:00
|
|
|
}
|
2021-12-13 09:34:55 +00:00
|
|
|
|
2016-12-30 23:20:38 +00:00
|
|
|
return h
|
|
|
|
}
|
|
|
|
|
2017-01-25 22:45:03 +00:00
|
|
|
func isHTML(acceptContent []string) bool {
|
|
|
|
for _, accept := range acceptContent {
|
|
|
|
if strings.Contains(accept, "text/html") {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2018-06-11 13:13:19 +00:00
|
|
|
func (handler *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2022-04-05 04:29:57 +00:00
|
|
|
if handler.wasInstanceDisabled() {
|
|
|
|
if r.RequestURI == "/" || r.RequestURI == "/index.html" {
|
|
|
|
http.Redirect(w, r, "/timeout.html", http.StatusTemporaryRedirect)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if strings.HasPrefix(r.RequestURI, "/timeout.html") {
|
|
|
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-01-25 22:45:03 +00:00
|
|
|
if !isHTML(r.Header["Accept"]) {
|
|
|
|
w.Header().Set("Cache-Control", "max-age=31536000")
|
|
|
|
} else {
|
|
|
|
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
|
|
}
|
2018-08-23 15:10:18 +00:00
|
|
|
|
|
|
|
w.Header().Add("X-XSS-Protection", "1; mode=block")
|
|
|
|
w.Header().Add("X-Content-Type-Options", "nosniff")
|
2017-05-29 20:10:36 +00:00
|
|
|
handler.Handler.ServeHTTP(w, r)
|
2016-12-30 23:20:38 +00:00
|
|
|
}
|