94 lines
2.0 KiB
Go
94 lines
2.0 KiB
Go
package server
|
|
|
|
import (
|
|
"acme-mana/src/conf"
|
|
"acme-mana/src/server/http_handler"
|
|
"context"
|
|
"embed"
|
|
"errors"
|
|
"github.com/gin-gonic/gin"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
//go:embed static/*
|
|
var staticFiles embed.FS
|
|
|
|
type HttpServer struct {
|
|
server *http.Server
|
|
status bool
|
|
engine *gin.Engine
|
|
}
|
|
|
|
func (s *HttpServer) Init() {
|
|
config := conf.Config()
|
|
var serverConf = config.Server
|
|
s.initServer(serverConf.Host, serverConf.Port)
|
|
}
|
|
|
|
// initServer 初始化
|
|
func (s *HttpServer) initServer(host string, port int) {
|
|
//gin.SetMode(gin.ReleaseMode)
|
|
s.engine = gin.Default()
|
|
s.register()
|
|
s.status = false
|
|
|
|
s.server = &http.Server{
|
|
Addr: host + ":" + strconv.Itoa(port),
|
|
Handler: s.engine,
|
|
}
|
|
}
|
|
|
|
func (s *HttpServer) Start() {
|
|
if s.status {
|
|
return
|
|
}
|
|
go func() {
|
|
if err := s.server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
|
|
log.Printf("listen: %s\n\n", err)
|
|
s.status = true
|
|
} else {
|
|
s.status = false
|
|
}
|
|
}()
|
|
}
|
|
|
|
func (s *HttpServer) Stop() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
defer cancel()
|
|
err := HttpInstance.server.Shutdown(ctx)
|
|
s.status = false
|
|
if err != nil {
|
|
log.Fatalln("HttpInstance Shutdown:", err)
|
|
}
|
|
}
|
|
|
|
func (s *HttpServer) Status() bool {
|
|
return s.status
|
|
}
|
|
|
|
func (s *HttpServer) register() {
|
|
service := s.engine
|
|
service.Use(gin.Logger())
|
|
service.Use(http_handler.GlobalErrorHandler())
|
|
|
|
fs := http.FS(staticFiles)
|
|
service.StaticFS("/s", fs)
|
|
|
|
certHandler := http_handler.CertHandlerInstance
|
|
certGroup := service.Group("/api/v1/cert", http_handler.AuthMiddleware())
|
|
certGroup.GET("/", certHandler.Get)
|
|
|
|
providerHandler := http_handler.ProviderHandlerInstance
|
|
providerGroup := service.Group("/api/v1/provider", http_handler.AuthMiddleware())
|
|
providerGroup.GET("/list", providerHandler.List)
|
|
providerGroup.GET("/map", providerHandler.Map)
|
|
|
|
confHandler := http_handler.ConfHandlerInstance
|
|
confGroup := service.Group("/api/v1", http_handler.AuthMiddleware())
|
|
confGroup.GET("/conf", confHandler.Get)
|
|
|
|
}
|