app/server/service.go

92 lines
1.9 KiB
Go
Raw Normal View History

2021-12-16 04:11:33 +00:00
package server
import (
"fmt"
"net"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog"
2021-12-20 17:07:33 +00:00
"github.com/rs/zerolog/log"
2021-12-16 04:11:33 +00:00
"github.com/spf13/viper"
2021-12-17 07:52:32 +00:00
"kumoly.io/kumoly/app/history"
2021-12-20 17:07:33 +00:00
"kumoly.io/kumoly/app/system"
2021-12-20 02:23:08 +00:00
"kumoly.io/kumoly/app/util"
2021-12-16 04:11:33 +00:00
)
type SkipLogFunc func(c *gin.Context) bool
2021-12-20 17:07:33 +00:00
var l zerolog.Logger
2021-12-16 04:11:33 +00:00
type Service struct {
Name string
Server *gin.Engine
API *gin.RouterGroup
SkipLog SkipLogFunc
Addr string
Allow *net.IPNet
l zerolog.Logger
}
2021-12-17 07:52:32 +00:00
var Server *gin.Engine
var API *gin.RouterGroup
2021-12-16 04:11:33 +00:00
func New(name string) *Service {
if viper.GetBool("prod") {
gin.SetMode(gin.ReleaseMode)
}
srv := &Service{
2021-12-16 17:33:26 +00:00
Name: name,
Server: gin.New(),
SkipLog: DefaultSkipLog,
Addr: fmt.Sprintf("%s:%s", viper.GetString("server.host"), viper.GetString("server.port")),
2021-12-16 04:11:33 +00:00
}
srv.Server.Use(srv.Default)
2021-12-17 07:52:32 +00:00
Server = srv.Server
2021-12-16 04:11:33 +00:00
srv.API = srv.Server.Group("/api")
2021-12-17 07:52:32 +00:00
API = srv.API
2021-12-16 04:11:33 +00:00
if ipnetstr := viper.GetString("server.allow"); ipnetstr != "" {
_, ipnet, err := net.ParseCIDR(ipnetstr)
if err != nil {
2021-12-20 02:23:08 +00:00
util.Klog.Panic().Str("service", "server.Service").Str("name", name).Err(err).Msg("ParseCIDR error")
2021-12-16 04:11:33 +00:00
}
srv.Allow = ipnet
}
return srv
}
func (srv *Service) Init() error {
2021-12-20 17:07:33 +00:00
l = util.Klog.With().Str("service", "server.Service").Str("name", srv.Name).Logger()
srv.l = system.SetupLogger(log.Logger, 2)
2021-12-16 04:11:33 +00:00
return nil
}
func (srv *Service) Load() error {
return nil
}
func (srv *Service) Main() error {
2021-12-20 17:07:33 +00:00
l.Info().Msgf("Server started on %s", srv.Addr)
2021-12-16 04:11:33 +00:00
go func() {
err := srv.Server.Run(srv.Addr)
if err != nil {
2021-12-17 07:52:32 +00:00
history.Send(history.Error().Nm("ServerStartError").Msg(err.Error()))
2021-12-20 17:07:33 +00:00
l.Panic().Err(err).Msg("Server.Run error")
2021-12-16 04:11:33 +00:00
}
}()
return nil
}
func (srv *Service) Del() {
}
func (srv Service) Health() error {
return nil
}
func (srv Service) GetName() string {
return "server.Service"
}
func (srv Service) GetDependencies() []string {
return nil
}
func (srv Service) IsService() bool {
return true
}