Statically save Content-Type in generated files as well.

This commit is contained in:
NI
2019-09-13 14:21:24 +08:00
parent e3f4079bdd
commit d03ab083d7
4 changed files with 48 additions and 24 deletions

View File

@@ -29,5 +29,5 @@ func serveFailure(
r *http.Request, r *http.Request,
l log.Logger, l log.Logger,
) error { ) error {
return serveStaticPage("error.html", ".html", err.Code(), w, r, l) return serveStaticPage("error.html", err.Code(), w, r, l)
} }

View File

@@ -29,5 +29,5 @@ type home struct {
} }
func (h home) Get(w http.ResponseWriter, r *http.Request, l log.Logger) error { func (h home) Get(w http.ResponseWriter, r *http.Request, l log.Logger) error {
return serveStaticCachePage("index.html", ".html", w, r, l) return serveStaticCachePage("index.html", w, r, l)
} }

View File

@@ -18,7 +18,6 @@
package controller package controller
import ( import (
"mime"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@@ -33,6 +32,7 @@ type staticData struct {
compressd []byte compressd []byte
compressdHash string compressdHash string
created time.Time created time.Time
contentType string
} }
func (s staticData) hasCompressed() bool { func (s staticData) hasCompressed() bool {
@@ -60,12 +60,11 @@ func serveStaticCacheData(
return ErrNotFound return ErrNotFound
} }
return serveStaticCachePage(dataName, fileExt, w, r, l) return serveStaticCachePage(dataName, w, r, l)
} }
func serveStaticCachePage( func serveStaticCachePage(
dataName string, dataName string,
fileExt string,
w http.ResponseWriter, w http.ResponseWriter,
r *http.Request, r *http.Request,
l log.Logger, l log.Logger,
@@ -110,13 +109,7 @@ func serveStaticCachePage(
w.Header().Add("Cache-Control", "public, max-age=31536000") w.Header().Add("Cache-Control", "public, max-age=31536000")
w.Header().Add("ETag", "\""+selectedDataHash+"\"") w.Header().Add("ETag", "\""+selectedDataHash+"\"")
mimeType := mime.TypeByExtension(fileExt) w.Header().Add("Content-Type", d.contentType)
if len(mimeType) > 0 {
w.Header().Add("Content-Type", mimeType)
} else {
w.Header().Add("Content-Type", "application/binary")
}
if compressEnabled { if compressEnabled {
w.Header().Add("Content-Encoding", "gzip") w.Header().Add("Content-Encoding", "gzip")
@@ -132,7 +125,6 @@ func serveStaticCachePage(
func serveStaticPage( func serveStaticPage(
dataName string, dataName string,
fileExt string,
code int, code int,
w http.ResponseWriter, w http.ResponseWriter,
r *http.Request, r *http.Request,
@@ -157,13 +149,7 @@ func serveStaticPage(
w.Header().Add("Vary", "Accept-Encoding") w.Header().Add("Vary", "Accept-Encoding")
} }
mimeType := mime.TypeByExtension(fileExt) w.Header().Add("Content-Type", d.contentType)
if len(mimeType) > 0 {
w.Header().Add("Content-Type", mimeType)
} else {
w.Header().Add("Content-Type", "application/binary")
}
if compressEnabled { if compressEnabled {
w.Header().Add("Content-Encoding", "gzip") w.Header().Add("Content-Encoding", "gzip")

View File

@@ -27,6 +27,7 @@ import (
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
"mime"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@@ -61,6 +62,7 @@ func parseStaticData(
compressedHash string, compressedHash string,
creation time.Time, creation time.Time,
data []byte, data []byte,
contentType string,
) staticData { ) staticData {
return staticData{ return staticData{
data: data[fileStart:fileEnd], data: data[fileStart:fileEnd],
@@ -68,6 +70,7 @@ func parseStaticData(
compressd: data[compressedStart:compressedEnd], compressd: data[compressedStart:compressedEnd],
compressdHash: compressedHash, compressdHash: compressedHash,
created: creation, created: creation,
contentType: contentType,
} }
} }
` `
@@ -79,11 +82,13 @@ import "compress/gzip"
import "encoding/base64" import "encoding/base64"
import "time" import "time"
import "crypto/sha256" import "crypto/sha256"
import "mime"
import "strings"
// WARNING: THIS GENERATION IS FOR DEBUG / DEVELOPMENT ONLY, DO NOT // WARNING: THIS GENERATION IS FOR DEBUG / DEVELOPMENT ONLY, DO NOT
// USE IT IN PRODUCTION! // USE IT IN PRODUCTION!
func staticFileGen(filePath string) staticData { func staticFileGen(fileName, filePath string) staticData {
content, readErr := ioutil.ReadFile(filePath) content, readErr := ioutil.ReadFile(filePath)
if readErr != nil { if readErr != nil {
@@ -93,7 +98,7 @@ func staticFileGen(filePath string) staticData {
compressed := bytes.NewBuffer(make([]byte, 0, 1024)) compressed := bytes.NewBuffer(make([]byte, 0, 1024))
compresser, compresserBuildErr := gzip.NewWriterLevel( compresser, compresserBuildErr := gzip.NewWriterLevel(
compressed, gzip.BestCompression) compressed, gzip.BestSpeed)
if compresserBuildErr != nil { if compresserBuildErr != nil {
panic(fmt.Sprintln("Cannot build data compresser:", compresserBuildErr)) panic(fmt.Sprintln("Cannot build data compresser:", compresserBuildErr))
@@ -122,8 +127,22 @@ func staticFileGen(filePath string) staticData {
return h.Sum(nil) return h.Sum(nil)
} }
fileExtDotIdx := strings.LastIndex(fileName, ".")
fileExt := ""
if fileExtDotIdx >= 0 {
fileExt = fileName[fileExtDotIdx:len(fileName)]
}
mimeType := mime.TypeByExtension(fileExt)
if len(mimeType) <= 0 {
mimeType = "application/binary"
}
return staticData{ return staticData{
data: content[0:contentLen], data: content[0:contentLen],
contentType: mimeType,
dataHash: base64.StdEncoding.EncodeToString( dataHash: base64.StdEncoding.EncodeToString(
getHash(content[0:contentLen])[:8]), getHash(content[0:contentLen])[:8]),
compressd: content[contentLen:], compressd: content[contentLen:],
@@ -136,7 +155,7 @@ func staticFileGen(filePath string) staticData {
var ( var (
staticPages = map[string]staticData{ staticPages = map[string]staticData{
{{ range . }}"{{ .Name }}": staticFileGen( {{ range . }}"{{ .Name }}": staticFileGen(
"{{ .Path }}", "{{ .Name }}", "{{ .Path }}",
), ),
{{ end }} {{ end }}
} }
@@ -171,6 +190,7 @@ func {{ .GOVariableName }}() (
string, // CompressedHash string, // CompressedHash
time.Time, // Time of creation time.Time, // Time of creation
[]byte, // Data []byte, // Data
string, // ContentType
) { ) {
created, createErr := time.Parse( created, createErr := time.Parse(
time.RFC1123, "{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 MST" }}") time.RFC1123, "{{ .Date.Format "Mon, 02 Jan 2006 15:04:05 MST" }}")
@@ -188,10 +208,12 @@ func {{ .GOVariableName }}() (
shrinkToFit := make([]byte, len(data)) shrinkToFit := make([]byte, len(data))
copy(shrinkToFit, data) copy(shrinkToFit, data)
data = nil
return {{ .FileStart }}, {{ .FileEnd }}, return {{ .FileStart }}, {{ .FileEnd }},
{{ .CompressedStart }}, {{ .CompressedEnd }}, {{ .CompressedStart }}, {{ .CompressedEnd }},
"{{ .ContentHash }}", "{{ .CompressedHash }}", created, shrinkToFit "{{ .ContentHash }}", "{{ .CompressedHash }}",
created, shrinkToFit, "{{ .ContentType }}"
} }
` `
) )
@@ -207,10 +229,12 @@ type parsedFile struct {
GOPackage string GOPackage string
Path string Path string
Data string Data string
Type string
FileStart int FileStart int
FileEnd int FileEnd int
CompressedStart int CompressedStart int
CompressedEnd int CompressedEnd int
ContentType string
ContentHash string ContentHash string
CompressedHash string CompressedHash string
Date time.Time Date time.Time
@@ -283,6 +307,19 @@ func parseFile(
goFileName := "Static" + strconv.FormatInt(int64(id), 10) goFileName := "Static" + strconv.FormatInt(int64(id), 10)
fileExtDotIdx := strings.LastIndex(name, ".")
fileExt := ""
if fileExtDotIdx >= 0 {
fileExt = name[fileExtDotIdx:len(name)]
}
mimeType := mime.TypeByExtension(fileExt)
if len(mimeType) <= 0 {
mimeType = "application/binary"
}
return parsedFile{ return parsedFile{
Name: name, Name: name,
GOVariableName: strings.Title(goFileName), GOVariableName: strings.Title(goFileName),
@@ -294,6 +331,7 @@ func parseFile(
FileEnd: contentLen, FileEnd: contentLen,
CompressedStart: contentLen, CompressedStart: contentLen,
CompressedEnd: len(content), CompressedEnd: len(content),
ContentType: mimeType,
ContentHash: base64.StdEncoding.EncodeToString( ContentHash: base64.StdEncoding.EncodeToString(
getHash(content[0:contentLen])[:8]), getHash(content[0:contentLen])[:8]),
CompressedHash: base64.StdEncoding.EncodeToString( CompressedHash: base64.StdEncoding.EncodeToString(