pkg/pwa/pwa.go 1.7 K raw
1
// Package pwa provides the shared service worker, registration script, and
2
// offline fallback page used by andromeda apps so read-only pages keep
3
// working offline.
4
//
5
// Apps opt in by calling Mount in their route setup and adding
6
// <script src="/pwa.js" defer></script> to their templates. Their
7
// site.webmanifest should include start_url, scope, and id.
8
package pwa
9
10
import (
11
	"embed"
12
	"net/http"
13
)
14
15
//go:embed static/sw.js static/pwa.js static/offline.html
16
var files embed.FS
17
18
// Mount registers the PWA routes on mux:
19
//   - GET /sw.js    the service worker (served from the root so its default
20
//     scope covers the whole origin)
21
//   - GET /pwa.js   the registration script included by app templates
22
//   - GET /offline  fallback page shown when an uncached navigation fails
23
func Mount(mux *http.ServeMux) {
24
	mux.HandleFunc("GET /sw.js", func(w http.ResponseWriter, r *http.Request) {
25
		serve(w, "static/sw.js", "application/javascript; charset=utf-8", true)
26
	})
27
	mux.HandleFunc("GET /pwa.js", func(w http.ResponseWriter, r *http.Request) {
28
		serve(w, "static/pwa.js", "application/javascript; charset=utf-8", true)
29
	})
30
	mux.HandleFunc("GET /offline", func(w http.ResponseWriter, r *http.Request) {
31
		serve(w, "static/offline.html", "text/html; charset=utf-8", false)
32
	})
33
}
34
35
func serve(w http.ResponseWriter, name, contentType string, noCache bool) {
36
	data, err := files.ReadFile(name)
37
	if err != nil {
38
		http.Error(w, "not found", http.StatusNotFound)
39
		return
40
	}
41
	w.Header().Set("Content-Type", contentType)
42
	if noCache {
43
		// Browsers cache service worker scripts for up to 24h by default.
44
		// Always revalidate so worker updates ship with each binary.
45
		w.Header().Set("Cache-Control", "no-cache")
46
	}
47
	_, _ = w.Write(data)
48
}