-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
84 lines (69 loc) · 2.08 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"github.com/jspaste/frontend/www"
"github.com/valyala/fasthttp"
"io"
"log"
"log/slog"
"net"
"os"
"strings"
"time"
)
func main() {
bindAddressEnv := getEnv("JSPF_BIND_ADDRESS", "[::]").(string)
portEnv := getEnv("JSPF_PORT", uint16(3000)).(uint16)
fs := &fasthttp.FS{
FS: www.Bundle(),
CompressedFileSuffixes: map[string]string{
"gzip": ".gz",
"br": ".br",
"zstd": ".zst",
},
Compress: true,
CompressBrotli: true,
CompressZstd: true,
}
requestHandler := fs.NewRequestHandler()
handler := func(ctx *fasthttp.RequestCtx) {
path := string(ctx.Request.URI().Path())
if !strings.Contains(path, ".") {
ctx.Request.SetRequestURI("/index.html")
ctx.Response.Header.Set("Content-Type", "text/html; charset=utf-8")
}
requestHandler(ctx)
if ctx.Response.StatusCode() == fasthttp.StatusNotFound {
ctx.Request.SetRequestURI("/index.html")
ctx.Response.Header.Set("Content-Type", "text/html; charset=utf-8")
requestHandler(ctx)
}
path = string(ctx.Request.URI().Path())
if strings.HasPrefix(path, "/assets/") {
ctx.Response.Header.Set("Cache-Control", "max-age=31536000, public, immutable")
} else if strings.HasSuffix(path, ".html") {
ctx.Response.Header.Set("Cache-Control", "max-age=0, public, must-revalidate")
} else {
ctx.Response.Header.Set("Cache-Control", "max-age=600, public")
}
ctx.Response.Header.Del("Last-Modified")
}
server := &fasthttp.Server{
GetOnly: true,
Handler: handler,
Logger: log.New(io.Discard, "", 0),
NoDefaultServerHeader: true,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
}
listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", bindAddressEnv, portEnv))
if err != nil {
slog.Error("Can't listen address;", "error", err)
os.Exit(1)
}
slog.Info("Server running;", "bindAddress", listen.Addr().(*net.TCPAddr).IP, "port", listen.Addr().(*net.TCPAddr).Port)
if err = server.Serve(listen); err != nil {
slog.Error("Unexpected server status;", "error", err)
os.Exit(1)
}
}