package ecpm_httpserver import ( "context" "errors" "gitea.youtukeji.com.cn/xiabin/youtu_ecpm/api/gin/controller" "gitea.youtukeji.com.cn/xiabin/youtu_ecpm/dao/query" ginzap "github.com/gin-contrib/zap" "github.com/gin-gonic/gin" "go.uber.org/zap" "net/http" "os" "os/signal" "time" ) type HttpServer struct { engine *gin.Engine log *zap.Logger } func NewHttpServer(logger *zap.Logger, q *query.Query) *HttpServer { r := gin.New() r.Use(ginzap.Ginzap(logger, time.RFC3339, true), ginzap.RecoveryWithZap(logger, true)) //初始化路由 InitRouter(r, logger, q) return &HttpServer{ engine: r, } } // Run 启动http服务 func (s *HttpServer) Run() { srv := &http.Server{ Addr: ":8080", Handler: s.engine, } go func() { // 服务连接 if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { s.log.Sugar().Fatalf("listen: %s\n", err) } }() // 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间) quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt) <-quit s.log.Sugar().Info("Shutdown Server ...") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { s.log.Sugar().Fatal("Server Shutdown:", err) } s.log.Sugar().Info("Server exiting") } func InitRouter(r *gin.Engine, logger *zap.Logger, q *query.Query) { { douyinCtl := controller.NewDouyinOpenApiController(logger, q) g := r.Group("/douyin") g.GET("/get_ecpm", douyinCtl.GetEcpm) g.GET("/code2userId", douyinCtl.Code2OpenId) } appUserCtl := controller.NewAppUserInfoController(logger, q) r.POST("/app_user_info/set_app_account", appUserCtl.SetAppAccount) { rankingCtl := controller.NewRankingList(logger, q) g := r.Group("/ranking") g.GET("/list", rankingCtl.GetRankingList) g.POST("/set_score", rankingCtl.SetScore) } { wechatCtl := controller.NewWechatOpenApiController(logger, q) g := r.Group("/wechat") g.GET("/code2userId", wechatCtl.Code2OpenId) } }