73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
"github.com/gogf/gf/v2/net/ghttp"
|
|
"github.com/gogf/gf/v2/os/gtime"
|
|
)
|
|
|
|
var Httpserver = g.Server()
|
|
|
|
func init() {
|
|
err := gtime.SetTimeZone("Asia/Shanghai")
|
|
if err != nil {
|
|
panic("设置时区失败")
|
|
}
|
|
Httpserver.SetOpenApiPath("/api.json")
|
|
Httpserver.BindMiddlewareDefault(ghttp.MiddlewareHandlerResponse)
|
|
Httpserver.BindMiddlewareDefault(func(r *ghttp.Request) {
|
|
r.Response.CORS(r.Response.DefaultCORSOptions())
|
|
r.Middleware.Next()
|
|
})
|
|
}
|
|
|
|
// RouteRegister 根据控制器结构体名称自动注册路由
|
|
func RouteRegister(controllers []interface{}) {
|
|
re := regexp.MustCompile("[A-Z]")
|
|
for _, t := range controllers {
|
|
sName := reflect.ValueOf(t).Elem().Type().Name()
|
|
convertedStr := re.ReplaceAllStringFunc(sName, func(s string) string {
|
|
return fmt.Sprintf("-%s", strings.ToLower(s))
|
|
})
|
|
if len(convertedStr) > 0 && convertedStr[0] == '-' {
|
|
convertedStr = convertedStr[1:]
|
|
}
|
|
Httpserver.Group("/"+convertedStr, func(group *ghttp.RouterGroup) {
|
|
group.Bind(t)
|
|
})
|
|
}
|
|
}
|
|
|
|
// ServeFrontend 配置前端静态文件服务
|
|
func ServeFrontend(distDir string) {
|
|
absDir, err := filepath.Abs(distDir)
|
|
if err != nil {
|
|
g.Log().Fatalf(nil, "前端目录路径无效: %v", err)
|
|
}
|
|
|
|
// 静态资源(JS/CSS/图片)
|
|
Httpserver.AddStaticPath("/assets", absDir+"/assets")
|
|
|
|
// SPA 兜底:非API路由返回 index.html
|
|
Httpserver.BindHandler("/*", func(r *ghttp.Request) {
|
|
indexFile := filepath.Join(absDir, "index.html")
|
|
if fileExists(indexFile) {
|
|
r.Response.ServeFile(indexFile)
|
|
} else {
|
|
r.Response.WriteStatus(404)
|
|
}
|
|
})
|
|
}
|
|
|
|
func fileExists(path string) bool {
|
|
_, err := os.Stat(path)
|
|
return err == nil
|
|
}
|