62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package routers
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
beego "github.com/beego/beego/v2/server/web"
|
|
"github.com/beego/beego/v2/server/web/context"
|
|
)
|
|
|
|
func RegisterPlatformSPA(spaDir string, hosts ...string) {
|
|
spaDir = strings.TrimSpace(spaDir)
|
|
if spaDir == "" || len(hosts) == 0 {
|
|
return
|
|
}
|
|
|
|
hostSet := make(map[string]struct{}, len(hosts))
|
|
for _, h := range hosts {
|
|
h = strings.ToLower(strings.TrimSpace(h))
|
|
if h != "" {
|
|
hostSet[h] = struct{}{}
|
|
}
|
|
}
|
|
|
|
passThrough := []string{
|
|
"/platform/", "/backend/", "/auth/", "/api/", "/app/",
|
|
"/uploads/", "/themes/",
|
|
"/.well-known/",
|
|
}
|
|
|
|
beego.InsertFilter("*", beego.BeforeStatic, func(ctx *context.Context) {
|
|
host := strings.ToLower(ctx.Request.Host)
|
|
if i := strings.IndexByte(host, ':'); i > 0 {
|
|
host = host[:i]
|
|
}
|
|
if _, ok := hostSet[host]; !ok {
|
|
return
|
|
}
|
|
|
|
path := ctx.Request.URL.Path
|
|
for _, p := range passThrough {
|
|
if strings.HasPrefix(path, p) {
|
|
return
|
|
}
|
|
}
|
|
|
|
rel := path
|
|
if rel == "" || rel == "/" {
|
|
rel = "/index.html"
|
|
}
|
|
target := spaDir + rel
|
|
|
|
if f, err := os.Stat(target); err == nil && !f.IsDir() {
|
|
http.ServeFile(ctx.ResponseWriter, ctx.Request, target)
|
|
return
|
|
}
|
|
|
|
ctx.Input.SetData("spa_fallback", true)
|
|
http.ServeFile(ctx.ResponseWriter, ctx.Request, spaDir+"/index.html")
|
|
})
|
|
} |