sdk_generate/internal/server/http.go

52 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package server
import (
"sdk-generator/internal/server/router"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/template/html/v2"
)
func NewHTTPServer(routerServer *router.RouterServer) *fiber.App {
//构建 server
app := initRoute()
router.SetupRoutes(app, routerServer)
return app
}
func initRoute() *fiber.App {
// 配置模板引擎
engine := html.New("./web/templates", ".html")
engine.Reload(true) // 开发时热重载
// 创建 Fiber 应用
app := fiber.New(fiber.Config{
AppName: "SDK Generator API",
Views: engine,
Prefork: false,
ServerHeader: "Fiber",
BodyLimit: 10 * 1024 * 1024, // 10MB
})
app.Use(recover.New())
app.Use(logger.New(logger.Config{
Format: "[${time}] ${status} - ${method} ${path} ${latency}\n",
}))
app.Use(func(c *fiber.Ctx) error {
// 设置 CORS 头
c.Set("Access-Control-Allow-Origin", "*")
c.Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// 如果是预检请求OPTIONS直接返回 204
if c.Method() == "OPTIONS" {
return c.SendStatus(fiber.StatusNoContent) // 204
}
// 继续处理后续中间件或路由
return c.Next()
})
return app
}