2017-05-23 18:56:10 +00:00
|
|
|
package handler
|
2016-12-30 23:20:38 +00:00
|
|
|
|
2017-01-25 22:45:03 +00:00
|
|
|
import (
|
2017-05-29 20:10:36 +00:00
|
|
|
"os"
|
|
|
|
|
|
|
|
"log"
|
2017-01-25 22:45:03 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
)
|
2016-12-30 23:20:38 +00:00
|
|
|
|
|
|
|
// FileHandler represents an HTTP API handler for managing static files.
|
|
|
|
type FileHandler struct {
|
|
|
|
http.Handler
|
2017-10-26 09:17:45 +00:00
|
|
|
Logger *log.Logger
|
2016-12-30 23:20:38 +00:00
|
|
|
}
|
|
|
|
|
2017-05-23 18:56:10 +00:00
|
|
|
// NewFileHandler returns a new instance of FileHandler.
|
2017-10-26 09:17:45 +00:00
|
|
|
func NewFileHandler(assetPublicPath string) *FileHandler {
|
2016-12-30 23:20:38 +00:00
|
|
|
h := &FileHandler{
|
2017-10-26 09:17:45 +00:00
|
|
|
Handler: http.FileServer(http.Dir(assetPublicPath)),
|
2017-05-29 20:10:36 +00:00
|
|
|
Logger: log.New(os.Stderr, "", log.LstdFlags),
|
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
|
|
|
|
}
|
|
|
|
|
2017-05-29 20:10:36 +00:00
|
|
|
func (handler *FileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
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")
|
|
|
|
}
|
2017-05-29 20:10:36 +00:00
|
|
|
handler.Handler.ServeHTTP(w, r)
|
2016-12-30 23:20:38 +00:00
|
|
|
}
|