| 1 | // Package darkmatter ships the shared CSS + fonts used by andromeda Go apps. |
| 2 | package darkmatter |
| 3 | |
| 4 | import ( |
| 5 | "embed" |
| 6 | "mime" |
| 7 | "net/http" |
| 8 | "path" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | //go:embed assets/darkmatter.css assets/index.html assets/fonts/* |
| 13 | var FS embed.FS |
| 14 | |
| 15 | // Mount registers the darkmatter routes (css, fonts, gallery) on mux. |
| 16 | // - <assetPrefix>/darkmatter.css |
| 17 | // - <assetPrefix>/fonts/{file} |
| 18 | // - /darkmatter and /darkmatter/ (gallery) |
| 19 | // |
| 20 | // assetPrefix is normally "/assets". The leading slash is required. |
| 21 | func Mount(mux *http.ServeMux, assetPrefix string) { |
| 22 | assetPrefix = strings.TrimRight(assetPrefix, "/") |
| 23 | if assetPrefix == "" { |
| 24 | assetPrefix = "/assets" |
| 25 | } |
| 26 | |
| 27 | mux.HandleFunc("GET "+assetPrefix+"/darkmatter.css", func(w http.ResponseWriter, r *http.Request) { |
| 28 | serve(w, "assets/darkmatter.css", "text/css; charset=utf-8") |
| 29 | }) |
| 30 | mux.HandleFunc("GET "+assetPrefix+"/fonts/{file}", func(w http.ResponseWriter, r *http.Request) { |
| 31 | file := r.PathValue("file") |
| 32 | ct := mime.TypeByExtension(path.Ext(file)) |
| 33 | if ct == "" { |
| 34 | ct = "application/octet-stream" |
| 35 | } |
| 36 | serve(w, "assets/fonts/"+file, ct) |
| 37 | }) |
| 38 | mux.HandleFunc("GET /darkmatter", func(w http.ResponseWriter, r *http.Request) { |
| 39 | serve(w, "assets/index.html", "text/html; charset=utf-8") |
| 40 | }) |
| 41 | mux.HandleFunc("GET /darkmatter/", func(w http.ResponseWriter, r *http.Request) { |
| 42 | serve(w, "assets/index.html", "text/html; charset=utf-8") |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | func serve(w http.ResponseWriter, name, contentType string) { |
| 47 | data, err := FS.ReadFile(name) |
| 48 | if err != nil { |
| 49 | http.Error(w, "not found", http.StatusNotFound) |
| 50 | return |
| 51 | } |
| 52 | w.Header().Set("Content-Type", contentType) |
| 53 | _, _ = w.Write(data) |
| 54 | } |