dispatch/server/serve_files.go

314 lines
6.9 KiB
Go
Raw Normal View History

2015-05-15 23:18:52 +00:00
package server
import (
"bytes"
"compress/gzip"
"crypto/md5"
"encoding/base64"
2017-04-14 02:33:44 +00:00
"io"
2015-05-15 23:18:52 +00:00
"io/ioutil"
2016-01-25 00:01:37 +00:00
"log"
2015-05-15 23:18:52 +00:00
"net/http"
2016-02-04 02:35:50 +00:00
"path"
2016-02-03 01:22:45 +00:00
"path/filepath"
2015-05-15 23:18:52 +00:00
"strconv"
"strings"
"time"
2017-04-14 02:33:44 +00:00
"github.com/dsnet/compress/brotli"
2016-03-01 00:51:26 +00:00
"github.com/spf13/viper"
2015-12-11 03:35:48 +00:00
"github.com/khlieng/dispatch/assets"
2015-05-15 23:18:52 +00:00
)
2017-04-14 02:33:44 +00:00
const longCacheControl = "public, max-age=31536000"
const disabledCacheControl = "no-cache, no-store, must-revalidate"
2016-02-03 01:22:45 +00:00
type File struct {
Path string
Asset string
2017-04-14 02:33:44 +00:00
GzipAsset []byte
2017-04-15 02:48:24 +00:00
Hash string
2016-02-03 01:22:45 +00:00
ContentType string
CacheControl string
2017-04-14 02:33:44 +00:00
Compressed bool
2016-02-03 01:22:45 +00:00
}
var (
2016-02-03 01:22:45 +00:00
files = []*File{
&File{
Path: "bundle.js",
2017-04-14 02:33:44 +00:00
Asset: "bundle.js.br",
ContentType: "text/javascript",
2017-04-14 02:33:44 +00:00
CacheControl: longCacheControl,
Compressed: true,
},
2016-02-03 01:22:45 +00:00
&File{
Path: "bundle.css",
2017-04-14 02:33:44 +00:00
Asset: "bundle.css.br",
ContentType: "text/css",
2017-04-14 02:33:44 +00:00
CacheControl: longCacheControl,
Compressed: true,
},
2016-02-03 01:22:45 +00:00
}
contentTypes = map[string]string{
".woff2": "font/woff2",
".woff": "application/font-woff",
".ttf": "application/x-font-ttf",
}
hstsHeader string
2016-02-03 18:42:07 +00:00
cspEnabled bool
)
2015-05-15 23:18:52 +00:00
func initFileServer() {
if !viper.GetBool("dev") {
data, err := assets.Asset(files[0].Asset)
if err != nil {
log.Fatal(err)
}
hash := md5.Sum(data)
2017-04-15 02:48:24 +00:00
files[0].Hash = base64.RawURLEncoding.EncodeToString(hash[:])
files[0].Path = "bundle." + files[0].Hash + ".js"
2017-04-14 02:33:44 +00:00
br, err := brotli.NewReader(bytes.NewReader(data), nil)
if err != nil {
log.Fatal(err)
}
buf := &bytes.Buffer{}
gzw, err := gzip.NewWriterLevel(buf, gzip.BestCompression)
if err != nil {
log.Fatal(err)
}
io.Copy(gzw, br)
gzw.Close()
files[0].GzipAsset = buf.Bytes()
data, err = assets.Asset(files[1].Asset)
if err != nil {
log.Fatal(err)
}
hash = md5.Sum(data)
2017-04-15 02:48:24 +00:00
files[1].Hash = base64.RawURLEncoding.EncodeToString(hash[:])
files[1].Path = "bundle." + files[1].Hash + ".css"
2017-04-14 02:33:44 +00:00
br.Reset(bytes.NewReader(data))
buf = &bytes.Buffer{}
gzw.Reset(buf)
io.Copy(gzw, br)
gzw.Close()
files[1].GzipAsset = buf.Bytes()
2016-02-03 01:22:45 +00:00
fonts, err := assets.AssetDir("font")
if err != nil {
log.Fatal(err)
}
for _, font := range fonts {
2017-04-14 02:33:44 +00:00
p := strings.TrimSuffix(font, ".br")
2016-02-03 01:22:45 +00:00
2017-04-14 02:33:44 +00:00
file := &File{
2016-02-04 02:35:50 +00:00
Path: path.Join("font", p),
Asset: path.Join("font", font),
ContentType: contentTypes[filepath.Ext(p)],
2017-04-14 02:33:44 +00:00
CacheControl: longCacheControl,
Compressed: strings.HasSuffix(font, ".br"),
}
if file.Compressed {
data, err = assets.Asset(file.Asset)
if err != nil {
log.Fatal(err)
}
br.Reset(bytes.NewReader(data))
buf = &bytes.Buffer{}
gzw.Reset(buf)
io.Copy(gzw, br)
gzw.Close()
file.GzipAsset = buf.Bytes()
}
files = append(files, file)
2016-02-03 01:22:45 +00:00
}
2016-02-03 18:42:07 +00:00
if viper.GetBool("https.hsts.enabled") && viper.GetBool("https.enabled") {
hstsHeader = "max-age=" + viper.GetString("https.hsts.max_age")
if viper.GetBool("https.hsts.include_subdomains") {
hstsHeader += "; includeSubDomains"
}
if viper.GetBool("https.hsts.preload") {
hstsHeader += "; preload"
}
}
2016-02-03 18:42:07 +00:00
cspEnabled = true
}
2015-05-15 23:18:52 +00:00
}
func serveFiles(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
2016-01-25 00:01:37 +00:00
serveIndex(w, r)
2015-05-15 23:18:52 +00:00
return
}
for _, file := range files {
if strings.HasSuffix(r.URL.Path, file.Path) {
2016-02-03 01:22:45 +00:00
serveFile(w, r, file)
2015-05-15 23:18:52 +00:00
return
}
}
2016-01-25 00:01:37 +00:00
serveIndex(w, r)
}
func serveIndex(w http.ResponseWriter, r *http.Request) {
session := handleAuth(w, r)
if session == nil {
log.Println("[Auth] No session")
w.WriteHeader(500)
return
}
2016-02-03 18:42:07 +00:00
if cspEnabled {
var connectSrc string
if r.TLS != nil {
connectSrc = "wss://" + r.Host
} else {
connectSrc = "ws://" + r.Host
}
2017-03-23 19:55:34 +00:00
w.Header().Set("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src data:; connect-src "+connectSrc)
2016-02-03 18:42:07 +00:00
}
2016-01-25 00:01:37 +00:00
w.Header().Set("Content-Type", "text/html")
2017-04-14 02:33:44 +00:00
w.Header().Set("Cache-Control", disabledCacheControl)
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "deny")
w.Header().Set("X-XSS-Protection", "1; mode=block")
if hstsHeader != "" {
w.Header().Set("Strict-Transport-Security", hstsHeader)
}
2016-01-25 00:01:37 +00:00
2017-04-15 02:48:24 +00:00
if pusher, ok := w.(http.Pusher); ok {
options := &http.PushOptions{
Header: http.Header{
"Accept-Encoding": r.Header["Accept-Encoding"],
},
}
cookie, err := r.Cookie("push")
if err != nil {
err = pusher.Push("/"+files[1].Path, options)
err = pusher.Push("/"+files[0].Path, options)
setPushCookie(w, r)
} else {
pushed := false
if files[1].Hash != cookie.Value[22:] {
pusher.Push("/"+files[1].Path, options)
pushed = true
}
if files[0].Hash != cookie.Value[:22] {
pusher.Push("/"+files[0].Path, options)
pushed = true
}
if pushed {
setPushCookie(w, r)
}
}
}
2016-01-25 00:01:37 +00:00
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
2016-01-25 00:01:37 +00:00
gzw := gzip.NewWriter(w)
2016-03-16 22:23:16 +00:00
IndexTemplate(gzw, getIndexData(r, session), files[1].Path, files[0].Path)
2016-01-25 00:01:37 +00:00
gzw.Close()
} else {
2016-03-16 22:23:16 +00:00
IndexTemplate(w, getIndexData(r, session), files[1].Path, files[0].Path)
2016-01-25 00:01:37 +00:00
}
2015-05-15 23:18:52 +00:00
}
2017-04-15 02:48:24 +00:00
func setPushCookie(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "push",
Value: files[0].Hash + files[1].Hash,
Path: "/",
Expires: time.Now().AddDate(1, 0, 0),
HttpOnly: true,
Secure: r.TLS != nil,
})
}
2016-02-03 01:22:45 +00:00
func serveFile(w http.ResponseWriter, r *http.Request, file *File) {
info, err := assets.AssetInfo(file.Asset)
2015-05-15 23:18:52 +00:00
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
if !modifiedSince(w, r, info.ModTime()) {
return
}
2016-02-03 01:22:45 +00:00
data, err := assets.Asset(file.Asset)
2015-05-15 23:18:52 +00:00
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
2016-02-03 01:22:45 +00:00
if file.CacheControl != "" {
w.Header().Set("Cache-Control", file.CacheControl)
}
w.Header().Set("Content-Type", file.ContentType)
2015-05-15 23:18:52 +00:00
2017-04-14 02:33:44 +00:00
if file.Compressed {
if strings.Contains(r.Header.Get("Accept-Encoding"), "br") {
w.Header().Set("Content-Encoding", "br")
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Write(data)
} else if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Length", strconv.Itoa(len(file.GzipAsset)))
w.Write(file.GzipAsset)
}
} else if !file.Compressed {
2016-02-03 01:22:45 +00:00
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Write(data)
2015-05-15 23:18:52 +00:00
} else {
2017-04-14 02:33:44 +00:00
gzr, err := gzip.NewReader(bytes.NewReader(file.GzipAsset))
2015-05-15 23:18:52 +00:00
buf, err := ioutil.ReadAll(gzr)
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(buf)))
w.Write(buf)
}
}
func modifiedSince(w http.ResponseWriter, r *http.Request, modtime time.Time) bool {
t, err := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since"))
if err == nil && modtime.Before(t.Add(1*time.Second)) {
w.WriteHeader(http.StatusNotModified)
return false
}
w.Header().Set("Last-Modified", modtime.UTC().Format(http.TimeFormat))
return true
}