Repository navigation
feat(gospa): serve a built single-page app and public files #176
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
SirLouen
wants to merge
12
commits into
main
Choose a base branch
from
feat/175
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,989
−3
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f19564a
test(gospa): pin how a built app answers its paths
SirLouen 5605d6e
test(gospa): pin how long a browser keeps each file of a built app
SirLouen 4577641
test(gospa): pin the server values written into the page
SirLouen 07cb078
test(gospa): pin how a public folder is served
SirLouen 98e147f
test(gospa): pin the rules a built app and a public folder share
SirLouen 11335e3
feat(gospa): write server values where a built page's head opens
SirLouen 78581a5
feat(gospa): send the files of a public folder and nothing else
SirLouen 7072ab4
feat(gospa): serve a built single-page app with its page for every ap…
SirLouen c882c65
test(gospa): run the scenarios against the brick
SirLouen 4564b42
feat(ci): test, lint and scan the GoSPA modules
SirLouen 122f276
docs(gospa): add the readme, the changelog and the examples
SirLouen 55e1e1e
docs(readme): list GoSPA among the modules
SirLouen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| version: "2" | ||
|
|
||
| linters: | ||
| default: standard | ||
| enable: | ||
| - cyclop | ||
| - depguard | ||
| - gocognit | ||
| - lll | ||
| - misspell | ||
| - revive | ||
| - unconvert | ||
| - unparam | ||
| settings: | ||
| cyclop: | ||
| max-complexity: 10 | ||
| gocognit: | ||
| min-complexity: 15 | ||
| lll: | ||
| line-length: 120 | ||
| revive: | ||
| rules: | ||
| - name: blank-imports | ||
| disabled: true | ||
| - name: exported | ||
| depguard: | ||
| rules: | ||
| dependency-purity: | ||
| list-mode: strict | ||
| allow: | ||
| - $gostd | ||
| - github.com/gopherium/framework/gospa | ||
| - golang.org/x/net/html | ||
| exclusions: | ||
| rules: | ||
| - path: _test\.go | ||
| linters: | ||
| - cyclop | ||
| - gocognit | ||
|
|
||
| formatters: | ||
| enable: | ||
| - gofmt | ||
| - goimports | ||
| settings: | ||
| goimports: | ||
| local-prefixes: | ||
| - github.com/gopherium/framework |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| # Changelog | ||
|
|
||
| All notable changes to GoSPA, the `gospa` module, are documented in | ||
| this file. The format follows | ||
| [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the | ||
| module follows [Semantic Versioning](https://semver.org/). While at | ||
| v0.x, minor releases may contain breaking changes. | ||
|
|
||
| Releases of this module are tagged `gospa/vX.Y.Z`. | ||
|
|
||
| ## [Unreleased] | ||
|
|
||
| ### Added | ||
|
|
||
| - `App`, a handler that serves a built single-page app from an `fs.FS`, sending `index.html` for every path that names no file outside `assets/`. | ||
| - A path under `assets/` that names no file answers not found. | ||
| - A hashed file under `assets/` is kept for `HashedMaxAge`, one year by default, and every other file and the page get `no-cache`. | ||
| - `App` fails when the build holds no `index.html`, when `HashedMaxAge` is below one second, and on a value with no name or a name given twice. | ||
| - `Meta`, server values the page carries as meta elements where its head opens. | ||
| - The page is read again each time it is sent and checked by a tag of the bytes sent. | ||
| - `Files`, a handler that sends the regular files of an `fs.FS` and nothing else. | ||
| - Both answer only GET and HEAD, never list a folder and never send a name starting with a dot, `.well-known` excepted. | ||
| - A path with an empty segment, or a segment that holds a tilde or ends in a dot or a space, answers not found. | ||
| - A file with no date, or dated at the Unix epoch, that can seek is checked by a tag of the bytes sent, worked out on every request. | ||
| - A file that cannot seek is read only as far as the answer needs, and gets the whole file when asked for several ranges. | ||
| - Types come from GoSPA's own table, `application/octet-stream` for an extension it does not know, and every file and page carries `X-Content-Type-Options: nosniff`. | ||
| - `AppOptions.NotFound` and `FilesOptions.NotFound` replace the plain not found answer. | ||
| - Requires `golang.org/x/net` v0.63.0. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| # GoSPA | ||
|
|
||
|  | ||
|
|
||
| Serve a built single-page app, and the files of a public folder, from a | ||
| Go program. | ||
|
|
||
| A build tool such as Vite turns a single-page app into one page, | ||
| `index.html`, and a folder of scripts, styles and fonts. The browser | ||
| loads the page once, and the app's own router shows a screen for each | ||
| address. Go's `http.FileServer` can send these files, but it lists | ||
| folders, sends hidden files such as `.env`, sets no cache rules and | ||
| cannot send the page for an address the app routes. GoSPA adds those | ||
| rules. | ||
|
|
||
| If you know Laravel, GoSPA does the job Nginx does in front of a | ||
| Laravel app: it sends the app for every address that names no file, | ||
| and serves the `public` folder file by file. | ||
|
|
||
| The guide is at <https://docs.gopherium.org/files/serving/>. | ||
|
|
||
| ## Serving a built app | ||
|
|
||
| ```go | ||
| //go:embed all:dist | ||
| var dist embed.FS | ||
|
|
||
| build, err := fs.Sub(dist, "dist") | ||
| if err != nil { | ||
| return err | ||
| } | ||
| admin, err := gospa.App(build, gospa.AppOptions{ | ||
| Meta: []gospa.Meta{{Name: "api-root", Content: "/api/"}}, | ||
| }) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| mux.Handle("/admin/", http.StripPrefix("/admin", admin)) | ||
| ``` | ||
|
|
||
| `App` fails when the build holds no `index.html`. Then it answers: | ||
|
|
||
| | The path | The answer | | ||
| | --- | --- | | ||
| | a file of the build | the file | | ||
| | `index.html` | the page | | ||
| | under `assets/`, no file | not found | | ||
| | anywhere else, no file | the page | | ||
|
|
||
| The page is read again each time it is sent, so a new build shows | ||
| without a restart. | ||
|
|
||
| ### How long a browser keeps a file | ||
|
|
||
| A hashed file is kept for `HashedMaxAge` without asking, one year when | ||
| it is zero, and `App` fails when it is below one second. A hashed file | ||
| is a file under `assets/` whose name ends in a dash, 8 | ||
| letters, digits, dashes or underscores, and an extension, as Vite names | ||
| `assets/index-DWLUpakq.js`. Its name changes whenever its content does. | ||
|
|
||
| The page and every other file get `no-cache`. The browser keeps them | ||
| but checks each one on every load, which costs a 304 with no body while | ||
| nothing changed. A file with a date is checked by its date. A file with | ||
| no date, as every embedded file is, is checked by a tag of the bytes | ||
| sent, worked out on every request. A file with no date that cannot seek | ||
| has nothing to be checked by, so the browser gets it again on every | ||
| load. The page is checked by a tag of the bytes sent, values included. | ||
|
|
||
| A name such as `assets/my-settings.js` looks hashed too. Vite writes no | ||
| such name under `assets/` unless your project has `public/assets/`. | ||
|
|
||
| ### Server values in the page | ||
|
|
||
| Each `Meta` becomes a meta element right where the head opens: | ||
|
|
||
| ```html | ||
| <head><meta name="api-root" content="/api/"> | ||
| ``` | ||
|
|
||
| The app reads it with | ||
| `document.querySelector('meta[name="api-root"]').content`. Names and | ||
| values are escaped. `App` fails on a value with no name or a name given | ||
| twice. | ||
|
|
||
| ## Serving a public folder | ||
|
|
||
| ```go | ||
| root, err := os.OpenRoot("uploads") | ||
| if err != nil { | ||
| return err | ||
| } | ||
| mux.Handle("/media/", http.StripPrefix("/media", gospa.Files(root.FS(), gospa.FilesOptions{}))) | ||
| ``` | ||
|
|
||
| `Files` sends each file by its path with `no-cache`. A missing file and | ||
| a folder answer not found, and a folder's `index.html` is sent only | ||
| when asked for by name. Use `os.OpenRoot` for a folder on disk, since | ||
| unlike `os.DirFS` it never follows a link out of the folder. | ||
|
|
||
| An uploaded HTML or SVG file can run scripts on your site. Serve | ||
| uploads from another domain, or check what people upload. | ||
|
|
||
| ## Rules both share | ||
|
|
||
| - Only GET and HEAD are answered. Any other method gets 405. | ||
| - A path segment that starts with a dot, such as `.env` or `.git`, | ||
| answers not found. `.well-known` is the one exception. | ||
| - A segment that holds a tilde or ends in a dot or a space answers not | ||
| found, since Windows reads `GIT~1` as `.git`. | ||
| - A path with an empty segment, such as `//app.js`, answers not found. | ||
| - Ranges and checks work as `http.ServeContent` answers them. A file | ||
| that cannot seek, such as one inside a zip, gets the whole file when | ||
| asked for several ranges. | ||
| - The type comes from the extension, by GoSPA's own table, the same on | ||
| every system. An extension it does not know gets | ||
| `application/octet-stream`, so the browser downloads the file. Every | ||
| file, page and plain not found answer carries | ||
| `X-Content-Type-Options: nosniff`, so the browser never guesses a type | ||
| from the bytes. | ||
| - `NotFound` replaces the plain 404 answer. | ||
|
|
||
| GoSPA serves the path it receives, so strip a prefix with | ||
| `http.StripPrefix`, as above. | ||
|
|
||
| The table knows `html`, `htm`, `css`, `js`, `mjs`, `json`, `map`, | ||
| `webmanifest`, `txt`, `xml`, `svg`, `png`, `jpg`, `jpeg`, `gif`, | ||
| `webp`, `avif`, `ico`, `woff`, `woff2`, `ttf`, `otf`, `wasm`, `pdf`, | ||
| `zip`, `mp3`, `m4a`, `wav`, `ogg`, `flac`, `mp4` and `webm`. | ||
|
|
||
| ## Testing | ||
|
|
||
| `go test ./...` runs the unit tests and the fuzz seeds. The scenarios | ||
| sit in `features/`, a module of their own, run with | ||
| `cd features && go test ./...`. | ||
|
|
||
| ## License | ||
|
|
||
| Apache-2.0. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package gospa | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "crypto/sha256" | ||
| "fmt" | ||
| "io/fs" | ||
| "net/http" | ||
| "regexp" | ||
| "strings" | ||
| "time" | ||
| ) | ||
|
|
||
| // DefaultHashedMaxAge is how long a browser keeps a hashed file when AppOptions sets no window. | ||
| const DefaultHashedMaxAge = 365 * 24 * time.Hour | ||
|
|
||
| // pageName is the file that holds the page of a built app. | ||
| const pageName = "index.html" | ||
|
|
||
| // assetsDir is the folder a build writes its hashed files to. | ||
| const assetsDir = "assets" | ||
|
|
||
| // hashedName matches a name under assets ending in a dash, 8 letters, digits, dashes or underscores and an extension. | ||
| var hashedName = regexp.MustCompile(`^assets/(?:[^/]+/)*[^/]*-[A-Za-z0-9_-]{8}(?:\.[A-Za-z0-9]+)+$`) | ||
|
|
||
| // AppOptions says how long App lets a browser keep hashed files, what its page carries and how it answers not found. | ||
| type AppOptions struct { | ||
| // HashedMaxAge is how long a browser keeps a hashed file, DefaultHashedMaxAge when zero, else one second or more. | ||
| HashedMaxAge time.Duration | ||
| // Meta holds the values the page carries in its head, in order. | ||
| Meta []Meta | ||
| // NotFound answers a path that names no file and may not get the page, http.NotFound when nil. | ||
| NotFound http.Handler | ||
| } | ||
|
|
||
| // app is the handler App returns. | ||
| type app struct { | ||
| folder folder | ||
| head []byte | ||
| hashed string | ||
| notFound http.Handler | ||
| } | ||
|
|
||
| // App returns a handler serving the built single-page app in fsys, its page for a path outside assets naming no file. | ||
| func App(fsys fs.FS, opts AppOptions) (http.Handler, error) { | ||
| if _, err := fs.ReadFile(fsys, pageName); err != nil { | ||
| return nil, fmt.Errorf("gospa: read the app page: %w", err) | ||
| } | ||
| head, err := metaElements(opts.Meta) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| hashed, err := hashedControl(opts.HashedMaxAge) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| return &app{folder: folder{fsys: fsys}, head: head, hashed: hashed, notFound: orNotFound(opts.NotFound)}, nil | ||
| } | ||
|
|
||
| // hashedControl returns the Cache-Control of a hashed file kept for maxAge, DefaultHashedMaxAge when zero. | ||
| func hashedControl(maxAge time.Duration) (string, error) { | ||
| if maxAge == 0 { | ||
| maxAge = DefaultHashedMaxAge | ||
| } | ||
| if maxAge < time.Second { | ||
| return "", fmt.Errorf("gospa: HashedMaxAge %v is below one second", maxAge) | ||
| } | ||
| return fmt.Sprintf("public, max-age=%d, immutable", int64(maxAge/time.Second)), nil | ||
| } | ||
|
|
||
| // ServeHTTP sends the file r names, the page when it names no file outside assets, or the not found answer. | ||
| func (a *app) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||
| if !readable(w, r) { | ||
| return | ||
| } | ||
| name, ok := fileName(r.URL.Path) | ||
| switch { | ||
| case !ok: | ||
| a.notFound.ServeHTTP(w, r) | ||
| case strings.EqualFold(name, pageName): | ||
| a.sendPage(w, r) | ||
| default: | ||
| a.sendFile(w, r, name) | ||
| } | ||
| } | ||
|
|
||
| // sendFile sends the file at name, or else the not found answer under assets and the page elsewhere. | ||
| func (a *app) sendFile(w http.ResponseWriter, r *http.Request, name string) { | ||
| open, ok := a.folder.open(name) | ||
| switch { | ||
| case ok: | ||
| a.folder.send(w, r, open, a.controlOf(name)) | ||
| case name == assetsDir || strings.HasPrefix(name, assetsDir+"/"): | ||
| a.notFound.ServeHTTP(w, r) | ||
| default: | ||
| a.sendPage(w, r) | ||
| } | ||
| } | ||
|
|
||
| // controlOf returns the Cache-Control of the file at name. | ||
| func (a *app) controlOf(name string) string { | ||
| if hashedName.MatchString(name) { | ||
| return a.hashed | ||
| } | ||
| return noCache | ||
| } | ||
|
|
||
| // sendPage sends the page with its values, tagged by the bytes sent and dated by nothing. | ||
| func (a *app) sendPage(w http.ResponseWriter, r *http.Request) { | ||
| page, err := fs.ReadFile(a.folder.fsys, pageName) | ||
| if err != nil { | ||
| http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| if a.head != nil { | ||
| page = withHead(page, a.head) | ||
| } | ||
| header := w.Header() | ||
| header.Set("ETag", tagOf(page)) | ||
| describe(header, pageName, noCache) | ||
| http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(page)) | ||
| } | ||
|
|
||
| // tagOf returns the strong entity tag of data. | ||
| func tagOf(data []byte) string { | ||
| sum := sha256.Sum256(data) | ||
| return tagFrom(sum[:]) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clarify that embedded builds require a restart.
The example uses
embed.FS, so replacingdiston disk does not update the running binary. Rebuild and restart the program to serve a new embedded build. The no-restart behavior applies to a filesystem that reflects the new files.