Files
tinyauth/internal/middleware/ui_middleware.go
Stavros 504a3b87b4 refactor: rework file structure (#325)
* wip: add middlewares

* refactor: use context fom middleware in handlers

* refactor: use controller approach in handlers

* refactor: move oauth providers into services (non-working)

* feat: create oauth broker service

* refactor: use a boostrap service to bootstrap the app

* refactor: split utils into smaller files

* refactor: use more clear name for frontend assets

* feat: allow customizability of resources dir

* fix: fix typo in ui middleware

* fix: validate resource file paths in ui middleware

* refactor: move resource handling to a controller

* feat: add some logging

* fix: configure middlewares before groups

* fix: use correct api path in login mutation

* fix: coderabbit suggestions

* fix: further coderabbit suggestions
2025-08-26 15:05:03 +03:00

57 lines
914 B
Go

package middleware
import (
"io/fs"
"net/http"
"os"
"strings"
"tinyauth/internal/assets"
"github.com/gin-gonic/gin"
)
type UIMiddleware struct {
UIFS fs.FS
UIFileServer http.Handler
}
func NewUIMiddleware() *UIMiddleware {
return &UIMiddleware{}
}
func (m *UIMiddleware) Init() error {
ui, err := fs.Sub(assets.FrontendAssets, "dist")
if err != nil {
return err
}
m.UIFS = ui
m.UIFileServer = http.FileServer(http.FS(ui))
return nil
}
func (m *UIMiddleware) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
switch strings.Split(c.Request.URL.Path, "/")[1] {
case "api":
c.Next()
return
case "resources":
c.Next()
return
default:
_, err := fs.Stat(m.UIFS, strings.TrimPrefix(c.Request.URL.Path, "/"))
if os.IsNotExist(err) {
c.Request.URL.Path = "/"
}
m.UIFileServer.ServeHTTP(c.Writer, c.Request)
c.Abort()
return
}
}
}