rts-sim-testing-service/init.go

58 lines
1.3 KiB
Go
Raw Normal View History

package main
import (
"fmt"
2023-07-28 14:45:35 +08:00
"net/http"
"time"
"go.uber.org/zap"
"joylink.club/bj-rtsts-server/db/dbquery"
2023-09-04 11:12:57 +08:00
"joylink.club/bj-rtsts-server/dto"
"github.com/gin-contrib/cors"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"joylink.club/bj-rtsts-server/config"
"joylink.club/bj-rtsts-server/db"
"joylink.club/bj-rtsts-server/logger"
)
func InitServer() *gin.Engine {
config.LoadConfig()
fmt.Println("数据源配置为:", config.Config.Datasource.Dsn)
err := logger.InitLogger()
if err != nil {
panic(err)
}
err = db.InitDb()
if err != nil {
panic(err)
}
dbquery.SetDefault(db.DB)
engine := gin.New()
conf := cors.DefaultConfig()
conf.AllowHeaders = []string{"*"}
conf.AllowAllOrigins = true
engine.Use(cors.New(conf))
engine.Use(ginzap.Ginzap(zap.L(), time.DateTime, false))
2023-07-28 14:45:35 +08:00
// gin panic 异常处理,默认处理为 engine.Use(ginzap.RecoveryWithZap(zap.L(), true))
engine.Use(ginzap.CustomRecoveryWithZap(zap.L(), true, func(c *gin.Context, e interface{}) {
2023-09-07 14:19:50 +08:00
switch e := e.(type) {
2023-07-28 14:45:35 +08:00
case error:
2023-09-07 14:19:50 +08:00
c.JSON(http.StatusInternalServerError, e)
2023-09-04 11:12:57 +08:00
case dto.ErrorDto:
2023-09-07 14:19:50 +08:00
e.Tip = dto.ErrorTipMap[e.Code]
c.JSON(http.StatusInternalServerError, e)
2023-07-28 14:45:35 +08:00
default:
c.JSON(http.StatusInternalServerError, e)
}
c.Writer.WriteHeaderNow()
c.Abort()
}))
return engine
}