package main import ( "bgm/consts" "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() { //GetConfig bgm.GetConfig() 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))) }, })) gormMap, err = bgm.GormMap(bgm.ConfigMap()[bgm.GetConfigKey(consts.DsnPre)]) 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) } }