add app service start/stop common logic

pull/196/head
Michael Li 2 years ago
parent a63744479b
commit 8e88500d8a

@ -3,37 +3,27 @@ package app
import ( import (
"net/http" "net/http"
"github.com/gin-contrib/cors" "github.com/rocboss/paopao-ce/internal/conf"
"github.com/gin-gonic/gin" "github.com/rocboss/paopao-ce/internal/servants"
) )
func NewWebEngine() *gin.Engine { type Service interface {
e := gin.New() Start()
e.HandleMethodNotAllowed = true Stop()
e.Use(gin.Logger()) Info() string
e.Use(gin.Recovery()) }
// 跨域配置
corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
corsConfig.AddAllowHeaders("Authorization")
e.Use(cors.New(corsConfig))
// 默认404
e.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"code": 404,
"msg": "Not Found",
})
})
// 默认405 func NewWebService() Service {
e.NoMethod(func(c *gin.Context) { e := newWebEngine()
c.JSON(http.StatusMethodNotAllowed, gin.H{ servants.RegisterWebServants(e)
"code": 405,
"msg": "Method Not Allowed",
})
})
return e return &webService{
server: &http.Server{
Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort,
Handler: e,
ReadTimeout: conf.ServerSetting.ReadTimeout,
WriteTimeout: conf.ServerSetting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
},
}
} }

@ -0,0 +1,62 @@
package app
import (
"context"
"fmt"
"log"
"net/http"
"github.com/fatih/color"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/conf"
)
type webService struct {
server *http.Server
}
func (s *webService) Start() {
if err := s.server.ListenAndServe(); err != nil {
log.Fatalf("run app failed: %s", err)
}
}
func (s *webService) Stop() {
s.server.Shutdown(context.Background())
}
func (s *webService) Info() string {
return fmt.Sprintf("PaoPao service listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort))
}
func newWebEngine() *gin.Engine {
e := gin.New()
e.HandleMethodNotAllowed = true
e.Use(gin.Logger())
e.Use(gin.Recovery())
// 跨域配置
corsConfig := cors.DefaultConfig()
corsConfig.AllowAllOrigins = true
corsConfig.AddAllowHeaders("Authorization")
e.Use(cors.New(corsConfig))
// 默认404
e.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"code": 404,
"msg": "Not Found",
})
})
// 默认405
e.NoMethod(func(c *gin.Context) {
c.JSON(http.StatusMethodNotAllowed, gin.H{
"code": 405,
"msg": "Method Not Allowed",
})
})
return e
}
Loading…
Cancel
Save