feat: 添加 MustStop 方法
feat: 添加 gin 统一执行 api 函数
This commit is contained in:
60
api/api.go
Normal file
60
api/api.go
Normal file
@ -0,0 +1,60 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"gitea.loveuer.com/yizhisec/packages/logger"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Api struct {
|
||||
Address string
|
||||
Name string
|
||||
App *gin.Engine
|
||||
TlsConfig *tls.Config
|
||||
}
|
||||
|
||||
func New(ctx context.Context, api *Api) (func(context.Context) error, error) {
|
||||
var (
|
||||
err error
|
||||
fn func(context.Context) error
|
||||
ln net.Listener
|
||||
)
|
||||
|
||||
if api == nil {
|
||||
return fn, errors.New("api is nil")
|
||||
}
|
||||
|
||||
if api.TlsConfig != nil {
|
||||
ln, err = tls.Listen("tcp", api.Address, api.TlsConfig)
|
||||
} else {
|
||||
ln, err = net.Listen("tcp", api.Address)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fn, err
|
||||
}
|
||||
|
||||
svc := &http.Server{
|
||||
Handler: api.App,
|
||||
}
|
||||
|
||||
go func() {
|
||||
logger.InfoCtx(ctx, "[%s] api svc running at: %s", api.Name, api.Address)
|
||||
if err = svc.Serve(ln); err != nil {
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
logger.ErrorCtx(ctx, "api svc run failed, err = %s", err.Error())
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
fn = func(timeout context.Context) error {
|
||||
logger.WarnCtx(ctx, "[%s] api svc shutdown...", api.Name)
|
||||
return svc.Shutdown(timeout)
|
||||
}
|
||||
|
||||
return fn, nil
|
||||
}
|
Reference in New Issue
Block a user