65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
|
package ecpm_httpserver
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"errors"
|
||
|
ginzap "github.com/gin-contrib/zap"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"go.uber.org/zap"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"os/signal"
|
||
|
"time"
|
||
|
"youtu_ecpm/api/gin/controller"
|
||
|
"youtu_ecpm/dao/query"
|
||
|
)
|
||
|
|
||
|
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)
|
||
|
r.GET("/get-ecpm", douyinCtl.GetEcpm)
|
||
|
r.GET("/code2openId", douyinCtl.Code2OpenId)
|
||
|
}
|