Files
packages/api/api.go
zhaoyupeng 7f49105b23 feat: 添加 MustStop 方法
feat: 添加 gin 统一执行 api 函数
2025-07-10 16:29:43 +08:00

61 lines
1.1 KiB
Go

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
}