Zeus/main.go

78 lines
1.9 KiB
Go
Raw Normal View History

2021-12-13 21:39:15 +08:00
package main
import (
2021-12-14 13:53:22 +08:00
"bgm/consts"
2021-12-13 21:39:15 +08:00
"bgm/handler"
"bgm/helper"
"bgm/model"
"context"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/requestid"
ctxLogger "github.com/luizsuper/ctxLoggers"
"go.uber.org/zap"
"gorm.io/gorm"
"os"
"runtime"
)
const (
createCategory = "/sts"
)
var (
gormMap = map[string]*gorm.DB{}
err error
handlerMap = make(map[string]func(ctx *fiber.Ctx) error, 0)
app = fiber.New(fiber.Config{
ErrorHandler: func(ctx *fiber.Ctx, err error) error {
return ctx.Status(fiber.StatusInternalServerError).JSON(model.Response{Message: "服务器内部错误"})
},
})
)
func init() {
2021-12-14 13:53:22 +08:00
//GetConfig
bgm.GetConfig()
2021-12-13 21:39:15 +08:00
handlerMap[createCategory] = handler.CreateCategoryH
//requestId
app.Use(requestid.New())
//logger
app.Use(logger.New(logger.Config{
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path} ${resBody}\n",
}))
//recover
app.Use(recover.New(recover.Config{
EnableStackTrace: true,
StackTraceHandler: func(c *fiber.Ctx, e interface{}) {
buf := make([]byte, 1024*1024)
buf = buf[:runtime.Stack(buf, false)]
ctxLogger.FError(c, "panic err", zap.String("stack", fmt.Sprintf("panic: %v\n%s\n", e, buf)))
},
}))
2021-12-14 13:53:22 +08:00
gormMap, err = bgm.GormMap(bgm.ConfigMap()[bgm.GetConfigKey(consts.DsnPre)])
2021-12-13 21:39:15 +08:00
if err != nil {
ctxLogger.FError(nil, "gorm err", zap.String("gorm", err.Error()))
os.Exit(-1)
}
app.Use(func(ctx *fiber.Ctx) error {
background := context.Background()
ctx.SetUserContext(context.WithValue(background, "local", gormMap["local"]))
return ctx.Next()
})
}
func main() {
app.Get("/*", func(ctx *fiber.Ctx) error {
defer ctx.UserContext().Done()
return handlerMap[ctx.Path()](ctx)
})
err := app.Listen(":8080")
if err != nil {
ctxLogger.Error(nil, "", zap.String("err", err.Error()))
os.Exit(-1)
}
}