83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"embed"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/joho/godotenv"
|
|
|
|
"sprintpadawan/api"
|
|
"sprintpadawan/lib"
|
|
)
|
|
|
|
type gzipResponseWriter struct {
|
|
io.Writer
|
|
http.ResponseWriter
|
|
}
|
|
|
|
var fingerprintPattern = regexp.MustCompile(`[-.][a-f0-9]{8,}\.`)
|
|
|
|
func (w gzipResponseWriter) Write(b []byte) (int, error) {
|
|
return w.Writer.Write(b)
|
|
}
|
|
|
|
func gzipMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
w.Header().Set("Vary", "Accept-Encoding")
|
|
|
|
gz := gzip.NewWriter(w)
|
|
defer gz.Close()
|
|
|
|
gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
|
|
next.ServeHTTP(gzw, r)
|
|
})
|
|
}
|
|
|
|
func cacheMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if fingerprintPattern.MatchString(filepath.Base(r.URL.Path)) {
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
} else {
|
|
w.Header().Set("Cache-Control", "public, max-age=3600")
|
|
}
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
//go:embed static templates
|
|
var embeddedFiles embed.FS
|
|
|
|
func main() {
|
|
// load .env file if it exists
|
|
_ = godotenv.Load()
|
|
|
|
lib.InitDB()
|
|
api.InitTemplates(embeddedFiles)
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
// serve static assets
|
|
staticHandler := http.FileServer(http.FS(embeddedFiles))
|
|
mux.Handle("/static/", cacheMiddleware(gzipMiddleware(staticHandler)))
|
|
|
|
api.SetupRoutes(mux)
|
|
|
|
addr := ":8080"
|
|
log.Printf("Starting SprintPadawan server on http://localhost%s", addr)
|
|
if err := http.ListenAndServe(addr, mux); err != nil {
|
|
log.Fatalf("server error: %v", err)
|
|
}
|
|
}
|