app/server/service.go

80 lines
1.6 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"
"github.com/rs/zerolog/log"
"github.com/spf13/viper"
)
type SkipLogFunc func(c *gin.Context) bool
type Service struct {
Name string
Server *gin.Engine
API *gin.RouterGroup
SkipLog SkipLogFunc
Addr string
Allow *net.IPNet
l zerolog.Logger
}
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)
srv.API = srv.Server.Group("/api")
if ipnetstr := viper.GetString("server.allow"); ipnetstr != "" {
_, ipnet, err := net.ParseCIDR(ipnetstr)
if err != nil {
log.Panic().Str("service", "server.Service").Str("name", name).Err(err).Msg("ParseCIDR error")
}
srv.Allow = ipnet
}
return srv
}
func (srv *Service) Init() error {
srv.l = log.With().Str("service", "server.Service").Str("name", srv.Name).Logger()
return nil
}
func (srv *Service) Load() error {
return nil
}
func (srv *Service) Main() error {
srv.l.Info().Msgf("Server started on %s", srv.Addr)
go func() {
err := srv.Server.Run(srv.Addr)
if err != nil {
srv.l.Panic().Err(err).Msg("Server.Run error")
}
}()
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
}