|
@@ -0,0 +1,68 @@
|
|
|
+package websubsvc
|
|
|
+
|
|
|
+import (
|
|
|
+ "github.com/gin-gonic/gin"
|
|
|
+ "net/http"
|
|
|
+ "path"
|
|
|
+)
|
|
|
+
|
|
|
+type FrontendUtil struct {
|
|
|
+ filesystem IFilesystem
|
|
|
+ vueHistoryMode bool
|
|
|
+ notFoundHdl gin.HandlerFunc
|
|
|
+ forbiddenHdl gin.HandlerFunc
|
|
|
+ fileServer http.Handler
|
|
|
+}
|
|
|
+
|
|
|
+func NewFrontendUtil(fs IFilesystem, vueHistoryMode bool) *FrontendUtil {
|
|
|
+ s := &FrontendUtil{
|
|
|
+ filesystem: fs,
|
|
|
+ vueHistoryMode: vueHistoryMode,
|
|
|
+ fileServer: http.FileServer(http.FS(fs)),
|
|
|
+ }
|
|
|
+ s.forbiddenHdl = s.DefaultForbiddenHandler
|
|
|
+ s.notFoundHdl = s.DefaultNotFoundHandler
|
|
|
+ return s
|
|
|
+}
|
|
|
+
|
|
|
+func (s *FrontendUtil) StaticFilesHandler(ctx *gin.Context) {
|
|
|
+ url := ctx.Request.URL.Path
|
|
|
+ fin, err := s.filesystem.Stat(path.Clean(url))
|
|
|
+ if err != nil {
|
|
|
+ if s.vueHistoryMode {
|
|
|
+ s.VueHistoryModeHandler(ctx)
|
|
|
+ return
|
|
|
+ } else {
|
|
|
+ s.notFoundHdl(ctx)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if fin.IsDir() {
|
|
|
+ _, xerr := s.filesystem.Stat(path.Join(path.Clean(url), "index.html"))
|
|
|
+ if xerr != nil {
|
|
|
+ if s.vueHistoryMode {
|
|
|
+ s.VueHistoryModeHandler(ctx)
|
|
|
+ return
|
|
|
+ } else {
|
|
|
+ s.forbiddenHdl(ctx)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ ctx.Request.URL.Path = url
|
|
|
+ s.fileServer.ServeHTTP(ctx.Writer, ctx.Request)
|
|
|
+}
|
|
|
+
|
|
|
+func (s *FrontendUtil) DefaultNotFoundHandler(ctx *gin.Context) {
|
|
|
+ ctx.Writer.WriteString("404 not found")
|
|
|
+ ctx.Status(404)
|
|
|
+}
|
|
|
+
|
|
|
+func (s *FrontendUtil) DefaultForbiddenHandler(ctx *gin.Context) {
|
|
|
+ ctx.Writer.WriteString("403 forbidden")
|
|
|
+ ctx.Status(403)
|
|
|
+}
|
|
|
+
|
|
|
+func (s *FrontendUtil) VueHistoryModeHandler(ctx *gin.Context) {
|
|
|
+ ctx.HTML(200, "index.html", &gin.H{})
|
|
|
+}
|