M6: serve and export modes, packaging
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
45105d292f
commit
00ee2a6d12
29 files changed
+1294
-75
No files matched your search
@@ -0,0 +1,283 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
contentSecurityPolicy = "default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'"
|
||||
cacheImmutable = "public, max-age=31536000, immutable"
|
||||
cacheShort = "public, max-age=60"
|
||||
)
|
||||
|
||||
var contentTypes = map[string]string{
|
||||
".html": "text/html; charset=utf-8",
|
||||
".json": "application/json",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".svg": "image/svg+xml",
|
||||
".webp": "image/webp",
|
||||
".avif": "image/avif",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".woff2": "font/woff2",
|
||||
".ico": "image/x-icon",
|
||||
".txt": "text/plain; charset=utf-8",
|
||||
}
|
||||
|
||||
var compressible = map[string]bool{".html": true, ".json": true, ".js": true, ".css": true, ".svg": true}
|
||||
|
||||
type Settings struct {
|
||||
Output string
|
||||
HotlinkAllow []string
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
settings atomic.Pointer[Settings]
|
||||
}
|
||||
|
||||
func NewHandler(settings Settings) *Handler {
|
||||
h := &Handler{}
|
||||
h.Update(settings)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *Handler) Update(settings Settings) {
|
||||
allow := make([]string, 0, len(settings.HotlinkAllow))
|
||||
for _, host := range settings.HotlinkAllow {
|
||||
allow = append(allow, strings.ToLower(strings.TrimSpace(host)))
|
||||
}
|
||||
settings.HotlinkAllow = allow
|
||||
h.settings.Store(&settings)
|
||||
}
|
||||
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
header := w.Header()
|
||||
header.Set("Content-Security-Policy", contentSecurityPolicy)
|
||||
header.Set("X-Content-Type-Options", "nosniff")
|
||||
header.Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
header.Set("Allow", "GET, HEAD")
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
settings := h.settings.Load()
|
||||
clean := path.Clean("/" + r.URL.Path)
|
||||
if !visible(clean) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(clean, "/t/") && hotlinked(r, settings.HotlinkAllow) {
|
||||
http.Error(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
root, err := currentRoot(settings.Output)
|
||||
if err != nil {
|
||||
http.Error(w, "no build published yet", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
name := filepath.Join(root, filepath.FromSlash(clean))
|
||||
info, err := os.Stat(name)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if info.IsDir() {
|
||||
index := filepath.Join(name, "index.html")
|
||||
indexInfo, err := os.Stat(index)
|
||||
if err != nil || !indexInfo.Mode().IsRegular() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if !strings.HasSuffix(r.URL.Path, "/") {
|
||||
target := clean + "/"
|
||||
if clean == "/" {
|
||||
target = "/"
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
target += "?" + r.URL.RawQuery
|
||||
}
|
||||
http.Redirect(w, r, target, http.StatusMovedPermanently)
|
||||
return
|
||||
}
|
||||
name, info, clean = index, indexInfo, path.Join(clean, "index.html")
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
serveFile(w, r, clean, name, info)
|
||||
}
|
||||
|
||||
func visible(clean string) bool {
|
||||
for _, part := range strings.Split(clean, "/") {
|
||||
if strings.HasPrefix(part, ".") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return !strings.HasSuffix(clean, ".gz")
|
||||
}
|
||||
|
||||
func hotlinked(r *http.Request, allow []string) bool {
|
||||
referer := r.Header.Get("Referer")
|
||||
if referer == "" {
|
||||
return false
|
||||
}
|
||||
u, err := url.Parse(referer)
|
||||
if err != nil || u.Host == "" {
|
||||
return true
|
||||
}
|
||||
host := strings.ToLower(u.Hostname())
|
||||
own := r.Host
|
||||
if split, _, err := net.SplitHostPort(r.Host); err == nil {
|
||||
own = split
|
||||
}
|
||||
if strings.EqualFold(own, host) {
|
||||
return false
|
||||
}
|
||||
for _, allowed := range allow {
|
||||
if host == allowed {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func currentRoot(output string) (string, error) {
|
||||
link := filepath.Join(output, "current")
|
||||
target, err := os.Readlink(link)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !filepath.IsAbs(target) {
|
||||
target = filepath.Join(output, target)
|
||||
}
|
||||
info, err := os.Stat(target)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", fs.ErrNotExist
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func cacheControl(clean string) string {
|
||||
for _, prefix := range []string{"/t/", "/og/", "/assets/"} {
|
||||
if strings.HasPrefix(clean, prefix) {
|
||||
return cacheImmutable
|
||||
}
|
||||
}
|
||||
return cacheShort
|
||||
}
|
||||
|
||||
func acceptsGzip(r *http.Request) bool {
|
||||
for _, part := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
|
||||
coding, params, _ := strings.Cut(strings.TrimSpace(part), ";")
|
||||
coding = strings.ToLower(strings.TrimSpace(coding))
|
||||
if coding != "gzip" && coding != "*" {
|
||||
continue
|
||||
}
|
||||
params = strings.ReplaceAll(strings.TrimSpace(params), " ", "")
|
||||
if q, ok := strings.CutPrefix(params, "q="); ok {
|
||||
if value, err := strconv.ParseFloat(q, 64); err == nil && value <= 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func serveFile(w http.ResponseWriter, r *http.Request, clean, name string, info fs.FileInfo) {
|
||||
header := w.Header()
|
||||
ext := strings.ToLower(path.Ext(clean))
|
||||
contentType, ok := contentTypes[ext]
|
||||
if !ok {
|
||||
contentType = mime.TypeByExtension(ext)
|
||||
}
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
header.Set("Content-Type", contentType)
|
||||
header.Set("Cache-Control", cacheControl(clean))
|
||||
variant := ""
|
||||
if compressible[ext] {
|
||||
header.Add("Vary", "Accept-Encoding")
|
||||
if acceptsGzip(r) {
|
||||
if gzInfo, err := os.Stat(name + ".gz"); err == nil && gzInfo.Mode().IsRegular() && gzInfo.ModTime().After(info.ModTime().Add(-time.Second)) {
|
||||
name, info, variant = name+".gz", gzInfo, "-gz"
|
||||
header.Set("Content-Encoding", "gzip")
|
||||
}
|
||||
}
|
||||
}
|
||||
f, err := os.Open(name)
|
||||
if err != nil {
|
||||
header.Del("Content-Encoding")
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
header.Set("ETag", fmt.Sprintf("\"%x-%x%s\"", info.ModTime().UnixNano(), info.Size(), variant))
|
||||
http.ServeContent(w, r, "", info.ModTime(), f)
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
http *http.Server
|
||||
done chan error
|
||||
}
|
||||
|
||||
func Start(listen string, handler http.Handler, logger *log.Logger) (*Server, error) {
|
||||
listener, err := net.Listen("tcp", listen)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
srv := &http.Server{
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 2 * time.Minute,
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
MaxHeaderBytes: 64 << 10,
|
||||
ErrorLog: logger,
|
||||
}
|
||||
s := &Server{http: srv, done: make(chan error, 1)}
|
||||
go func() {
|
||||
err := srv.Serve(listener)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
err = nil
|
||||
}
|
||||
s.done <- err
|
||||
}()
|
||||
logger.Printf("serve: listening on http://%s", listener.Addr())
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown(timeout time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
err := s.http.Shutdown(ctx)
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
err = s.http.Close()
|
||||
}
|
||||
if serveErr := <-s.done; serveErr != nil && err == nil {
|
||||
err = serveErr
|
||||
}
|
||||
return err
|
||||
}
|
||||
Reference in new issue
Block a user