82 lines
1.8 KiB
Go
82 lines
1.8 KiB
Go
package routers
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"server/pkg/verifyfiles"
|
|
|
|
beego "github.com/beego/beego/v2/server/web"
|
|
"github.com/beego/beego/v2/server/web/context"
|
|
)
|
|
|
|
func appRoot() string {
|
|
candidates := make([]string, 0, 2)
|
|
if wd, err := os.Getwd(); err == nil {
|
|
candidates = append(candidates, wd)
|
|
}
|
|
if beego.AppPath != "" {
|
|
candidates = append(candidates, beego.AppPath)
|
|
}
|
|
return appRootFrom(candidates)
|
|
}
|
|
|
|
func appRootFrom(candidates []string) string {
|
|
for _, base := range candidates {
|
|
if base == "" {
|
|
continue
|
|
}
|
|
if _, err := os.Stat(filepath.Join(base, "conf", "app.conf")); err == nil {
|
|
return base
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func RegisterVerifyFiles(dir string, exts string, hosts ...string) {
|
|
dir = strings.TrimSpace(dir)
|
|
if dir == "-" {
|
|
return
|
|
}
|
|
if dir == "" {
|
|
dir = filepath.Join(appRoot(), verifyfiles.DefaultDir)
|
|
}
|
|
|
|
resolver, err := verifyfiles.New(verifyfiles.Config{
|
|
Dir: dir,
|
|
Exts: exts,
|
|
Hosts: strings.Join(hosts, ","),
|
|
})
|
|
if err != nil {
|
|
log.Printf("[verify] 根路径验证文件功能未启用: %v", err)
|
|
return
|
|
}
|
|
if resolver == nil {
|
|
return
|
|
}
|
|
|
|
if err := os.MkdirAll(resolver.Dir(), 0o755); err != nil {
|
|
log.Printf("[verify] 创建验证文件目录失败: %v", err)
|
|
}
|
|
|
|
beego.InsertFilter("*", beego.BeforeStatic, func(ctx *context.Context) {
|
|
if ctx.Request.Method != http.MethodGet && ctx.Request.Method != http.MethodHead {
|
|
return
|
|
}
|
|
if !resolver.AllowHost(ctx.Request.Host) {
|
|
return
|
|
}
|
|
full, ok := resolver.Resolve(ctx.Request.URL.Path)
|
|
if !ok {
|
|
return
|
|
}
|
|
ctx.Output.Header("Cache-Control", "public, max-age=300")
|
|
http.ServeFile(ctx.ResponseWriter, ctx.Request, full)
|
|
})
|
|
|
|
log.Printf("[verify] 根路径验证文件目录: %s,允许扩展名: %v", resolver.Dir(), resolver.Exts())
|
|
}
|