optimize main initial logic for new service init

pull/196/head
Michael Li 2 years ago
parent 6570286a4e
commit 3c47f48c42
No known key found for this signature in database

@ -1,4 +1,5 @@
App: # APP基础设置项
RunMode: debug
AttachmentIncomeRate: 0.8
MaxCommentCount: 10
DefaultContextTimeout: 60
@ -17,8 +18,19 @@ Features:
Slim: ["Base", "Sqlite3", "LocalOSS", "LoggerFile", "OSS:TempDir"]
Base: ["Redis", "PhoneBind"]
Docs: ["Docs:OpenAPI"]
Deprecated: ["Deprecated:OldWeb"]
Option: ["SimpleCacheIndex"]
Sms: "SmsJuhe"
WebServer: # Web服务
HttpIp: 0.0.0.0
HttpPort: 8010
ReadTimeout: 60
WriteTimeout: 60
DocsServer: # 开发文档服务
HttpIp: 0.0.0.0
HttpPort: 8011
ReadTimeout: 60
WriteTimeout: 60
SmsJuhe:
Gateway: https://v.juhe.cn/sms/send
Key:

@ -5,6 +5,7 @@ go 1.18
require (
github.com/Masterminds/semver/v3 v3.1.1
github.com/afocus/captcha v0.0.0-20191010092841-4bd1f21c8868
github.com/alimy/mir/v3 v3.0.0-alpha.3
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible
github.com/allegro/bigcache/v3 v3.0.2
github.com/bytedance/sonic v1.5.0
@ -39,7 +40,6 @@ require (
gorm.io/plugin/dbresolver v1.1.0
gorm.io/plugin/soft_delete v1.1.0
modernc.org/sqlite v1.17.3
github.com/alimy/mir/v3 v3.0.0
)
require (
@ -132,7 +132,3 @@ require (
modernc.org/strutil v1.1.1 // indirect
modernc.org/token v1.0.0 // indirect
)
replace (
github.com/alimy/mir/v3 => ../../alimy/mir
)

@ -142,6 +142,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0=
github.com/alexflint/go-filemutex v1.1.0/go.mod h1:7P4iRhttt/nUvUOrYIhcpMzv2G6CY9UnI16Z+UJqRyk=
github.com/alimy/mir/v3 v3.0.0-alpha.3 h1:/GyBC0G041NIP3W62im8DtAwxRPSfSaivSQK6MV9fFc=
github.com/alimy/mir/v3 v3.0.0-alpha.3/go.mod h1:ybhT2ijOiDn0lLwWzIY6vXdv+uzZrctS7VFfczcXBWU=
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible h1:9gWa46nstkJ9miBReJcN8Gq34cBFbzSpQZVVT9N09TM=
github.com/aliyun/aliyun-oss-go-sdk v2.2.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM=

@ -24,6 +24,8 @@ var (
PostgresSetting *PostgresSettingS
Sqlite3Setting *Sqlite3SettingS
ServerSetting *ServerSettingS
WebServerSetting *ServerSettingS
DocsServerSetting *ServerSettingS
AppSetting *AppSettingS
CacheIndexSetting *CacheIndexSettingS
SimpleCacheIndexSetting *SimpleCacheIndexSettingS
@ -60,6 +62,8 @@ func setupSetting(suite []string, noDefault bool) error {
objects := map[string]any{
"App": &AppSetting,
"Server": &ServerSetting,
"WebServer": &WebServerSetting,
"DocsServer": &DocsServerSetting,
"CacheIndex": &CacheIndexSetting,
"SimpleCacheIndex": &SimpleCacheIndexSetting,
"BigCacheIndex": &BigCacheIndexSetting,
@ -138,3 +142,10 @@ func GetOssDomain() string {
}
return uri + AliOSSSetting.Domain + "/"
}
func RunMode() string {
if !cfg.If("Deprecated:OldWeb") {
return ServerSetting.RunMode
}
return AppSetting.RunMode
}

@ -54,6 +54,7 @@ type ServerSettingS struct {
}
type AppSettingS struct {
RunMode string
MaxCommentCount int64
AttachmentIncomeRate float64
DefaultContextTimeout time.Duration

@ -118,6 +118,78 @@ func NewRouter() *gin.Engine {
return e
}
func RegisterRoute(e *gin.Engine) {
// 按需注册 docs、静态资源、LocalOSS 路由
{
registerDocs(e)
registerStatick(e)
cfg.Be("LocalOSS", func() {
routeLocalOSS(e)
})
}
// v1 group api
r := e.Group("/v1")
// 获取version
r.GET("/", api.Version)
// 用户登录
r.POST("/auth/login", api.Login)
// 用户注册
r.POST("/auth/register", api.Register)
// 获取验证码
r.GET("/captcha", api.GetCaptcha)
// 发送验证码
r.POST("/captcha", api.PostCaptcha)
// 无鉴权路由组
noAuthApi := r.Group("/")
{
// 获取动态详情
noAuthApi.GET("/post", api.GetPost)
// 获取动态评论
noAuthApi.GET("/post/comments", api.GetPostComments)
// 获取话题列表
noAuthApi.GET("/tags", api.GetPostTags)
}
// 宽松鉴权路由组
looseApi := r.Group("/").Use(chain.JwtLoose())
{
// 获取广场流
looseApi.GET("/posts", api.GetPostList)
// 获取用户动态列表
looseApi.GET("/user/posts", api.GetUserPosts)
// 获取用户基本信息
looseApi.GET("/user/profile", api.GetUserProfile)
}
// 鉴权路由组
authApi := r.Group("/").Use(chain.JWT())
privApi := r.Group("/").Use(chain.JWT()).Use(chain.Priv())
adminApi := r.Group("/").Use(chain.JWT()).Use(chain.Admin())
// 核心路由注册
routeCore(authApi, privApi, adminApi)
// 支付宝路由注册
cfg.Be("Alipay", func() {
routeAlipay(r, authApi)
})
// Relationship相关路由注册
routeRelationship(authApi)
}
func routeCore(authApi gin.IRoutes, privApi gin.IRoutes, adminApi gin.IRoutes) {
// 同步索引
authApi.GET("/sync/index", api.SyncSearchIndex)

@ -8,23 +8,16 @@ import (
"github.com/gin-gonic/gin"
)
type httpService interface {
Service
registerRoute(e *gin.Engine)
}
type baseHttpService struct {
baseService
server *httpServer
}
func (s *baseHttpService) Init() error {
func (s *baseHttpService) registerRoute(h func(e *gin.Engine)) {
if s.server.status() != httpServerStarted {
s.registerRoute(s.server.e)
h(s.server.e)
}
return nil
}
func (s *baseHttpService) Start() error {
@ -37,13 +30,3 @@ func (s *baseHttpService) Start() error {
func (s *baseHttpService) Stop() error {
return s.server.stop()
}
func (s *baseHttpService) registerRoute(e *gin.Engine) {
// default empty
}
func newBaseHttpService(s *httpServer) httpService {
return &baseHttpService{
server: s,
}
}

@ -28,7 +28,7 @@ func (baseService) String() string {
}
func InitService() (ss []Service) {
ss = append(ss, newWebService())
ss = append(ss, newWebService(), newOldWebService())
for _, s := range ss {
if err := s.Init(); err != nil {

@ -16,19 +16,20 @@ import (
)
type webService struct {
httpService
*baseHttpService
}
func (s *webService) Name() string {
return "WebService"
}
func (s *webService) registerRoute(e *gin.Engine) {
servants.RegisterWebServants(e)
func (s *webService) Init() error {
s.registerRoute(servants.RegisterWebServants)
return nil
}
func (s *webService) String() string {
return fmt.Sprintf("PaoPao service listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort))
return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.WebServerSetting.HttpIp, conf.WebServerSetting.HttpPort))
}
func newWebEngine() *gin.Engine {
@ -63,7 +64,7 @@ func newWebEngine() *gin.Engine {
}
func newWebService() Service {
addr := conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort
addr := conf.WebServerSetting.HttpIp + ":" + conf.WebServerSetting.HttpPort
server := httpServerFrom(addr, func() *httpServer {
engine := newWebEngine()
return &httpServer{
@ -71,13 +72,15 @@ func newWebService() Service {
server: &http.Server{
Addr: addr,
Handler: engine,
ReadTimeout: conf.ServerSetting.ReadTimeout,
WriteTimeout: conf.ServerSetting.WriteTimeout,
ReadTimeout: conf.WebServerSetting.ReadTimeout,
WriteTimeout: conf.WebServerSetting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
},
}
})
return &webService{
httpService: newBaseHttpService(server),
baseHttpService: &baseHttpService{
server: server,
},
}
}

@ -0,0 +1,53 @@
// Copyright 2022 ROC. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package service
import (
"fmt"
"net/http"
"github.com/fatih/color"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/servants/web/routers"
)
type oldWebService struct {
*baseHttpService
}
func (s *oldWebService) Name() string {
return "OldWebService"
}
func (s *oldWebService) Init() error {
s.registerRoute(routers.RegisterRoute)
return nil
}
func (s *oldWebService) String() string {
return fmt.Sprintf("listen on %s\n", color.GreenString("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort))
}
func newOldWebService() Service {
addr := conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort
server := httpServerFrom(addr, func() *httpServer {
engine := newWebEngine()
return &httpServer{
e: engine,
server: &http.Server{
Addr: addr,
Handler: engine,
ReadTimeout: conf.ServerSetting.ReadTimeout,
WriteTimeout: conf.ServerSetting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
},
}
})
return &oldWebService{
baseHttpService: &baseHttpService{
server: server,
},
}
}

@ -8,14 +8,16 @@ import (
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"github.com/fatih/color"
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal"
"github.com/rocboss/paopao-ce/internal/conf"
"github.com/rocboss/paopao-ce/internal/servants/web/routers"
"github.com/rocboss/paopao-ce/internal/service"
"github.com/rocboss/paopao-ce/pkg/debug"
"github.com/rocboss/paopao-ce/pkg/util"
)
@ -51,24 +53,41 @@ func flagParse() {
flag.Parse()
}
func main() {
gin.SetMode(conf.ServerSetting.RunMode)
router := routers.NewRouter()
s := &http.Server{
Addr: conf.ServerSetting.HttpIp + ":" + conf.ServerSetting.HttpPort,
Handler: router,
ReadTimeout: conf.ServerSetting.ReadTimeout,
WriteTimeout: conf.ServerSetting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
func runService(ss []service.Service) {
gin.SetMode(conf.RunMode())
fmt.Fprintf(color.Output, "\nstarting run service...\n\n")
for _, s := range ss {
go func(s service.Service) {
fmt.Fprintf(color.Output, "%s[start] - %s\n", s.Name(), s)
if err := s.Start(); err != nil {
log.Fatalf("%s[start] - occurs on error: %s\n", s.Name(), err)
}
}(s)
}
quit := make(chan os.Signal, 1)
// kill (no param) default send syscall.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
fmt.Fprintf(color.Output, "\nshutting down server...\n\n")
for _, s := range ss {
if err := s.Stop(); err != nil {
fmt.Fprintf(color.Output, "%s[stop] - occurs on error: %s\n", s.Name(), err)
}
fmt.Fprintf(color.Output, "%s[stop] - finish...\n", s.Name())
}
}
func main() {
util.PrintHelloBanner(debug.VersionInfo())
fmt.Fprintf(color.Output, "PaoPao service listen on %s\n",
color.GreenString(fmt.Sprintf("http://%s:%s", conf.ServerSetting.HttpIp, conf.ServerSetting.HttpPort)),
)
if err := s.ListenAndServe(); err != nil {
log.Fatalf("run app failed: %s", err)
if ss := service.InitService(); len(ss) > 0 {
runService(ss)
} else {
fmt.Fprintf(color.Output, "no service need start so just exit")
}
}

@ -23,8 +23,4 @@ var (
GatewayAppKeyClosed = NewError(10113, "网关请求APP KEY已停用")
GatewayParamSignError = NewError(10114, "网关请求参数签名错误")
GatewayTooManyRequests = NewError(10115, "网关请求频次超限")
FileUploadFailed = NewError(10200, "文件上传失败")
FileInvalidExt = NewError(10201, "文件类型不合法")
FileInvalidSize = NewError(10202, "文件大小超限")
)

Loading…
Cancel
Save