-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
83 lines (64 loc) · 2.55 KB
/
Copy pathmain.go
File metadata and controls
83 lines (64 loc) · 2.55 KB
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
package main
import (
"net/http"
"strconv"
"gofr.dev/pkg/gofr"
"zop.dev/static-server/internal/config"
)
const defaultStaticFilePath = `./static`
const indexHTML = "/index.html"
const htmlExtension = ".html"
const rootPath = "/"
// configLookup is the slice of gofr's config this server reads. Declaring it
// here lets the empty-value resolution below be exercised directly, rather than
// only through a running app.
type configLookup interface {
GetOrDefault(key, fallback string) string
}
// resolveOrDefault returns the configured value for key, falling back when the
// key is absent *or* present but empty.
//
// gofr's GetOrDefault only covers absent. The shipped configs/.env sets these
// keys with empty values, so a deployment supplying STATIC_DIR_PATH through the
// environment would otherwise receive "" and silently root every lookup at the
// process working directory — serving pages while loading zero `_headers` rules,
// the kind of half-working state that never gets noticed.
func resolveOrDefault(cfg configLookup, key, fallback string) string {
if value := cfg.GetOrDefault(key, fallback); value != "" {
return value
}
return fallback
}
func main() {
app := gofr.New()
staticFilePath := resolveOrDefault(app.Config, "STATIC_DIR_PATH", defaultStaticFilePath)
// SPA_MODE needs no such guard: ParseBool rejects "" and leaves the same
// false the default would have produced.
spaMode, _ := strconv.ParseBool(app.Config.GetOrDefault("SPA_MODE", "false"))
defaultExtension := resolveOrDefault(app.Config, "DEFAULT_EXTENSION", htmlExtension)
handler := &staticFileHandler{
staticFilePath: staticFilePath,
spaMode: spaMode,
defaultExtension: defaultExtension,
}
app.OnStart(func(ctx *gofr.Context) error {
handler.fs = ctx.File
if err := config.HydrateFile(ctx.File, app.Config); err != nil {
ctx.Logger.Error(err.Error())
}
// Read once at startup rather than per request. Absent file → no rules
// → responses are byte-for-byte what they are today.
handler.headerRules = loadHeaderRules(ctx.File, staticFilePath)
// The resolved directory is logged with the count: "0 rules" is normal
// for a site without the file, but indistinguishable from a misrooted
// path unless the path is on the line too.
ctx.Logger.Infof("loaded %d %s rule(s) from %s", len(handler.headerRules), headersFileName, staticFilePath)
return nil
})
app.UseMiddleware(func(next http.Handler) http.Handler {
handler.next = next
return http.HandlerFunc(handler.ServeHTTP)
})
app.AddStaticFiles("/", staticFilePath)
app.Run()
}