package main import ( "bgm/consts" "bgm/handler" "bgm/helper" "bgm/model" "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" "os" "runtime" ) const ( category = "/category" script = "/script" ) type handleM map[string]func(ctx *fiber.Ctx, mysqlMap bgm.MysqlMap) error var ( mysqlMap = make(bgm.MysqlMap, 0) err error app = fiber.New(fiber.Config{ ErrorHandler: func(ctx *fiber.Ctx, err error) error { return ctx.Status(fiber.StatusInternalServerError).JSON(model.Response{Message: "服务器内部错误"}) }, }) ) var ( getHandlerMap = make(handleM, 0) postHandlerMap = make(handleM, 0) putHandlerMap = make(handleM, 0) delHandlerMap = make(handleM, 0) ) func init() { //GetConfig bgm.GetConfig() getHandlerMap[category] = 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, consts.PanicError, zap.String(consts.ErrorReason, fmt.Sprintf("panic: %v\n%s\n", e, buf))) }, })) mysqlMap, err = bgm.GormMap(bgm.ConfigMap()[bgm.GetConfigKey(consts.DsnPre)]) if err != nil { ctxLogger.FError(nil, consts.GormError, zap.String(consts.ErrorReason, err.Error())) os.Exit(-1) } routerInit() } func routerInit() { getHandlerMap[category] = handler.GetCategoryH } func serverStart() { port := bgm.GetEnvDefault(consts.Port, consts.PortDefault) err = app.Listen(fmt.Sprintf(":%v", port)) if err != nil { ctxLogger.Error(nil, "", zap.String("err", err.Error())) os.Exit(-1) } } func main() { app.Get(fmt.Sprintf("%v", category), func(ctx *fiber.Ctx) error { return getHandlerMap[category](ctx, mysqlMap) }) app.Get(fmt.Sprintf("%v/:page/:size", script), func(ctx *fiber.Ctx) error { return getHandlerMap[script](ctx, mysqlMap) }) serverStart() }