Update sub.go

This commit is contained in:
Hassan Dashtizadeh 2025-03-05 23:16:48 +04:00 committed by GitHub
parent 590567bfa0
commit c7ec62def1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -3,11 +3,14 @@ package sub
import (
"context"
"crypto/tls"
"embed"
"html/template"
"io"
"io/fs"
"net"
"net/http"
"os"
"strconv"
"x-ui/config"
"x-ui/logger"
"x-ui/util/common"
@ -15,9 +18,13 @@ import (
"x-ui/web/network"
"x-ui/web/service"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
)
//go:embed html/*
var htmlFS embed.FS
type Server struct {
httpServer *http.Server
listener net.Listener
@ -37,6 +44,48 @@ func NewServer() *Server {
}
}
func (s *Server) getHtmlFiles() ([]string, error) {
files := make([]string, 0)
dir, _ := os.Getwd()
err := fs.WalkDir(os.DirFS(dir), "sub/html", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
files = append(files, path)
return nil
})
if err != nil {
return nil, err
}
return files, nil
}
func (s *Server) getHtmlTemplate(funcMap template.FuncMap) (*template.Template, error) {
t := template.New("").Funcs(funcMap)
err := fs.WalkDir(htmlFS, "html", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
newT, err := t.ParseFS(htmlFS, path+"/*.html")
if err != nil {
// ignore
return nil
}
t = newT
}
return nil
})
if err != nil {
return nil, err
}
return t, nil
}
func (s *Server) initRouter() (*gin.Engine, error) {
if config.IsDebug() {
gin.SetMode(gin.DebugMode)
@ -48,6 +97,33 @@ func (s *Server) initRouter() (*gin.Engine, error) {
engine := gin.Default()
basePath, err := s.settingService.GetBasePath()
if err != nil {
return nil, err
}
engine.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{basePath + "panel/API/"})))
engine.Use(func(c *gin.Context) {
c.Set("base_path", basePath)
})
// set static files and template
if config.IsDebug() {
// for development
files, err := s.getHtmlFiles()
if err != nil {
return nil, err
}
engine.LoadHTMLFiles(files...)
} else {
// for production
template, err := s.getHtmlTemplate(engine.FuncMap)
if err != nil {
return nil, err
}
engine.SetHTMLTemplate(template)
}
subDomain, err := s.settingService.GetSubDomain()
if err != nil {
return nil, err