Skip to content
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

feat(spa): fallback for single page applications #48

Merged
merged 1 commit into from
May 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,26 @@ You can always just run the `go-bindata` tool, and then

use

import "github.com/elazarl/go-bindata-assetfs"
...
http.Handle("/",
http.FileServer(
&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "data"}))
```go
import "github.com/elazarl/go-bindata-assetfs"
...
http.Handle("/",
http.FileServer(
&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "data"}))
```

to serve files embedded from the `data` directory.

## SPA applications

For single page applications you can use `Fallback: "index.html"` in AssetFS context, so if route doesn't match the pattern it will fallback to file specified.

example

```go
import "github.com/elazarl/go-bindata-assetfs"
...
http.Handle("/",
http.FileServer(
&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "data", Fallback: "index.html"}))
```
14 changes: 11 additions & 3 deletions assetfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ type AssetFS struct {
AssetInfo func(path string) (os.FileInfo, error)
// Prefix would be prepended to http requests
Prefix string
// Fallback file that is served if no other is found
Fallback string
}

func (fs *AssetFS) Open(name string) (http.File, error) {
Expand All @@ -153,9 +155,13 @@ func (fs *AssetFS) Open(name string) (http.File, error) {
}
return NewAssetFile(name, b, timestamp), nil
}
if children, err := fs.AssetDir(name); err == nil {
return NewAssetDirectory(name, children, fs), nil
} else {
children, err := fs.AssetDir(name)

if err != nil {
if len(fs.Fallback) > 0 {
return fs.Open(fs.Fallback)
}

// If the error is not found, return an error that will
// result in a 404 error. Otherwise the server returns
// a 500 error for files not found.
Expand All @@ -164,4 +170,6 @@ func (fs *AssetFS) Open(name string) (http.File, error) {
}
return nil, err
}

return NewAssetDirectory(name, children, fs), nil
}