Created
October 17, 2024 09:57
-
-
Save lechuhuuha/0e868538ffbc171e9b8db35c49a9b7c4 to your computer and use it in GitHub Desktop.
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
package http | |
import ( | |
"embed" | |
"errors" | |
"io/fs" | |
"net/http" | |
"path/filepath" | |
"github.com/gin-contrib/static" | |
) | |
var ( | |
//go:embed all:static/* | |
staticFS embed.FS | |
) | |
type SpaHandler struct { | |
httpFS http.FileSystem | |
root string | |
fs *embed.FS | |
} | |
func NewSpaHandler() *SpaHandler { | |
return &SpaHandler{ | |
fs: &staticFS, | |
httpFS: http.FS(staticFS), | |
root: "static", | |
} | |
} | |
func (s *SpaHandler) Exists(_, _ string) bool { | |
return true | |
} | |
func (s *SpaHandler) Open(name string) (http.File, error) { | |
p := filepath.Join(s.root, name) | |
_, err := fs.Stat(s.fs, p) | |
if err != nil { | |
var rootErr *fs.PathError | |
if !errors.As(err, &rootErr) { | |
return nil, err | |
} | |
if !errors.Is(rootErr.Err, fs.ErrNotExist) { | |
return nil, err | |
} | |
p = filepath.Join(s.root, static.INDEX) | |
} | |
return s.httpFS.Open(p) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment