40 lines
904 B
Go
40 lines
904 B
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func main() {
|
|
// Folder to serve
|
|
dir := "."
|
|
|
|
// File server handler
|
|
fs := http.FileServer(http.Dir(dir))
|
|
|
|
// Wrap the file server to add caching headers
|
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ext := strings.ToLower(filepath.Ext(r.URL.Path))
|
|
|
|
// Set long caching for static assets
|
|
switch ext {
|
|
case ".css", ".js", ".woff", ".woff2", ".ttf", ".eot", ".svg", ".png", ".jpg", ".jpeg", ".gif":
|
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
|
default:
|
|
// Optional: short caching for HTML so you always get latest page
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
}
|
|
|
|
fs.ServeHTTP(w, r)
|
|
})
|
|
|
|
addr := ":8080"
|
|
log.Printf("Serving %s on http://localhost%s\n", dir, addr)
|
|
err := http.ListenAndServe(addr, handler)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|