feat: 完成前后端打包

This commit is contained in:
2026-03-27 18:39:53 +08:00
parent b0db64bd7b
commit 21251c6e07
8 changed files with 201 additions and 8 deletions

12
internal/conf/var.go Normal file
View File

@@ -0,0 +1,12 @@
package conf
// 构建信息
var (
Mode string = "debug"
Version string = "unknown"
BuildAt string = "unknown"
GitAuthor string = "unknown"
GitEmail string = "unknown"
GitCommit string = "unknown"
)

View File

@@ -1,16 +1,27 @@
package router
import (
"ckwk/internal/conf"
"ckwk/internal/handler"
"ckwk/internal/middleware"
"ckwk/internal/schedule"
"ckwk/pkg/log"
"ckwk/web"
"io/fs"
"net/http"
"strings"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func SetupRouter() *gin.Engine {
if conf.Mode != gin.ReleaseMode {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*://*", "http://localhost:5173"},
@@ -22,7 +33,16 @@ func SetupRouter() *gin.Engine {
}))
wkHandler := handler.NewWKHandler()
sessionMiddleware := middleware.SessionMiddleware(wkHandler.Session)
schedule.StartCron(wkHandler.Session)
// schedule.StartCron(wkHandler.Session)
dist, err := fs.Sub(web.Public, web.DistDir)
if err != nil {
log.Fatal("failed to read dist dir", zap.Error(err))
}
distHTTP := http.FS(dist)
r.StaticFS("/js", http.FS(mustSub(dist, "js")))
r.StaticFS("/assets", http.FS(mustSub(dist, "assets")))
r.StaticFileFS("/favicon.ico", "favicon.ico", distHTTP)
api := r.Group("/api")
{
@@ -40,5 +60,23 @@ func SetupRouter() *gin.Engine {
}
}
r.NoRoute(func(ctx *gin.Context) {
if strings.HasPrefix(ctx.Request.URL.Path, "/api") {
ctx.JSON(404, gin.H{"code": 404, "msg": "API not found"})
return
}
ctx.Header("Content-Type", "text/html; charset=utf-8")
http.ServeFileFS(ctx.Writer, ctx.Request, dist, "index.html")
})
return r
}
// 辅助函数:简化 fs.Sub 的错误处理
func mustSub(f fs.FS, dir string) fs.FS {
sub, err := fs.Sub(f, dir)
if err != nil {
panic("failed to find static dir: " + dir)
}
return sub
}