18 "github.com/mjl-/mox/mlog"
21// WebappFile serves a merged HTML and JS webapp as a single compressed, cacheable
22// file. It merges the JS into the HTML at first load, caches a gzipped version
23// that is generated on first need, and responds with a Last-Modified header.
24type WebappFile struct {
25 HTML, JS []byte // Embedded html/js data.
26 HTMLPath, JSPath string // Paths to load html/js from during development.
27 CustomStem string // For trying to read css/js customizations from $configdir/$stem.{css,js}.
32 mtime time.Time // For Last-Modified and conditional request.
35// FallbackMtime returns a time to use for the Last-Modified header in case we
36// cannot find a file, e.g. when used in production.
37func FallbackMtime(log mlog.Log) time.Time {
38 p, err := os.Executable()
39 log.Check(err, "finding executable for mtime")
42 log.Check(err, "stat on executable for mtime")
47 log.Info("cannot find executable for webappfile mtime, using current time")
51func (a *WebappFile) serverError(log mlog.Log, w http.ResponseWriter, err error, action string) {
52 log.Errorx("serve webappfile", err, slog.String("msg", action))
53 http.Error(w, "500 - internal server error", http.StatusInternalServerError)
56// Serve serves a combined file, with headers for caching and possibly gzipped.
57func (a *WebappFile) Serve(ctx context.Context, log mlog.Log, w http.ResponseWriter, r *http.Request) {
58 // We typically return the embedded file, but during development it's handy
60 fhtml, _ := os.Open(a.HTMLPath)
64 fjs, _ := os.Open(a.JSPath)
72 var diskmtime time.Time
74 if fhtml != nil && fjs != nil {
75 sth, err := fhtml.Stat()
77 a.serverError(log, w, err, "stat html")
80 stj, err := fjs.Stat()
82 a.serverError(log, w, err, "stat js")
86 maxmtime := sth.ModTime()
87 if stj.ModTime().After(maxmtime) {
88 maxmtime = stj.ModTime()
92 refreshdisk = maxmtime.After(a.mtime) || a.combined == nil
96 html, err = io.ReadAll(fhtml)
98 a.serverError(log, w, err, "reading html")
101 js, err = io.ReadAll(fjs)
103 a.serverError(log, w, err, "reading js")
110 // Check mtime of css/js files.
111 var haveCustomCSS, haveCustomJS bool
112 checkCustomMtime := func(ext string, have *bool) bool {
113 path := ConfigDirPath(a.CustomStem + "." + ext)
114 if fi, err := os.Stat(path); err != nil {
115 if !errors.Is(err, fs.ErrNotExist) {
116 a.serverError(log, w, err, "stat customization file")
119 } else if mtm := fi.ModTime(); mtm.After(diskmtime) {
125 if !checkCustomMtime("css", &haveCustomCSS) || !checkCustomMtime("js", &haveCustomJS) {
128 // Detect removal of custom files.
129 if fi, err := os.Stat(ConfigDirPath(".")); err == nil && fi.ModTime().After(diskmtime) {
130 diskmtime = fi.ModTime()
134 refreshdisk = refreshdisk || diskmtime.After(a.mtime)
146 if refreshdisk || a.combined == nil {
147 var customCSS, customJS []byte
150 customCSS, err = os.ReadFile(ConfigDirPath(a.CustomStem + ".css"))
152 a.serverError(log, w, err, "read custom css file")
157 customJS, err = os.ReadFile(ConfigDirPath(a.CustomStem + ".js"))
159 a.serverError(log, w, err, "read custom js file")
164 cssp := []byte(`/* css placeholder */`)
165 cssi := bytes.Index(html, cssp)
167 a.serverError(log, w, errors.New("css placeholder not found"), "generating combined html")
170 jsp := []byte(`/* js placeholder */`)
171 jsi := bytes.Index(html, jsp)
173 a.serverError(log, w, errors.New("js placeholder not found"), "generating combined html")
178 fmt.Fprintf(&b, "/* Custom CSS by admin from $configdir/%s.css: */\n", a.CustomStem)
180 b.Write(html[cssi+len(cssp) : jsi])
181 fmt.Fprintf(&b, "// Custom JS by admin from $configdir/%s.js:\n", a.CustomStem)
183 fmt.Fprintf(&b, "\n// Javascript is generated from typescript, don't modify the javascript because changes will be lost.\n")
185 b.Write(html[jsi+len(jsp):])
191 a.mtime = FallbackMtime(log)
198 if a.combinedGzip == nil {
200 gzw, err := gzip.NewWriterLevel(&b, gzip.BestCompression)
202 _, err = gzw.Write(out)
208 a.serverError(log, w, err, "gzipping combined html")
211 a.combinedGzip = b.Bytes()
213 origSize = int64(len(out))
223 w.Header().Set("Content-Type", "text/html; charset=utf-8")
224 http.ServeContent(gzipInjector{w, gz, origSize}, r, "", mtime, bytes.NewReader(out))
227// gzipInjector is a http.ResponseWriter that optionally injects a
228// Content-Encoding: gzip header, only in case of status 200 OK. Used with
229// http.ServeContent to serve gzipped content if the client supports it. We cannot
230// just unconditionally add the content-encoding header, because we don't know
231// enough if we will be sending data: http.ServeContent may be sending a "not
232// modified" response, and possibly others.
233type gzipInjector struct {
234 http.ResponseWriter // Keep most methods.
239// WriteHeader adds a Content-Encoding: gzip header before actually writing the
240// headers and status.
241func (w gzipInjector) WriteHeader(statusCode int) {
242 if w.gz && statusCode == http.StatusOK {
243 w.ResponseWriter.Header().Set("Content-Encoding", "gzip")
244 if lw, ok := w.ResponseWriter.(interface{ SetUncompressedSize(int64) }); ok {
245 lw.SetUncompressedSize(w.origSize)
248 w.ResponseWriter.WriteHeader(statusCode)
251// AcceptsGzip returns whether the client accepts gzipped responses.
252func AcceptsGzip(r *http.Request) bool {
253 s := r.Header.Get("Accept-Encoding")
254 t := strings.Split(s, ",")
255 for _, e := range t {
256 e = strings.TrimSpace(e)
257 tt := strings.Split(e, ";")
258 if len(tt) > 1 && t[1] == "q=0" {