Skip to content

Commit

Permalink
Merge pull request #48 from jkuri/feat-fallback
Browse files Browse the repository at this point in the history
feat(spa): fallback for single page applications
  • Loading branch information
elazarl authored May 9, 2020
2 parents d0111fe + c766eaf commit 234c15e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
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
}

0 comments on commit 234c15e

Please sign in to comment.