yao/service/static.go
Max f55fc7b374 ⚠️ BREAKING: Rename XGen to CUI and update license terms
1. Major Changes:
   - Migrate all XGen references to CUI
   - Update project naming conventions across codebase

2. License Updates:
   - Revise open source license terms
   - Update copyright and usage conditions

This is a breaking change that requires updates in dependent projects.
2025-05-18 12:16:45 +08:00

91 lines
1.8 KiB
Go

package service
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/yao/data"
"github.com/yaoapp/yao/service/fs"
"github.com/yaoapp/yao/share"
)
// AppFileServer static file server
var AppFileServer http.Handler
// CUIFileServerV1 CUI v1.0
var CUIFileServerV1 http.Handler = http.FileServer(data.CuiV1())
// AdminRoot cache
var AdminRoot = ""
// AdminRootLen cache
var AdminRootLen = 0
var rewriteRules = []rewriteRule{}
type rewriteRule struct {
Pattern *regexp.Regexp
Replacement string
}
// SetupStatic setup static file server
func SetupStatic() error {
setupAdminRoot()
setupRewrite()
// Disable gzip compression for static files
if share.App.Static.DisableGzip {
AppFileServer = http.FileServer(fs.Dir("public"))
return nil
}
AppFileServer = gzipHandler(http.FileServer(fs.Dir("public")))
return nil
}
func setupRewrite() {
if share.App.Static.Rewrite != nil {
for _, rule := range share.App.Static.Rewrite {
pattern := ""
replacement := ""
for key, value := range rule {
pattern = key
replacement = value
break
}
re, err := regexp.Compile(pattern)
if err != nil {
log.Error("Invalid rewrite rule: %s", pattern)
continue
}
rewriteRules = append(rewriteRules, rewriteRule{
Pattern: re,
Replacement: replacement,
})
}
}
}
// rewrite path
func setupAdminRoot() (string, int) {
if AdminRoot != "" {
return AdminRoot, AdminRootLen
}
adminRoot := "/yao/"
if share.App.AdminRoot != "" {
root := strings.TrimPrefix(share.App.AdminRoot, "/")
root = strings.TrimSuffix(root, "/")
adminRoot = fmt.Sprintf("/%s/", root)
}
adminRootLen := len(adminRoot)
AdminRoot = adminRoot
AdminRootLen = adminRootLen
return AdminRoot, AdminRootLen
}