1 Star 0 Fork 0

谈子文/keyauth-tz

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
http.go 2.85 KB
一键复制 编辑 原始数据 按行查看 历史
谈子文 提交于 2023-10-25 15:11 . 优化
package protocol
import (
"context"
"fmt"
"net/http"
"time"
restfulspec "github.com/emicklei/go-restful-openapi/v2"
"github.com/emicklei/go-restful/v3"
"github.com/infraboard/mcube/logger"
"github.com/infraboard/mcube/logger/zap"
"github.com/infraboard/mcube/app"
"gitee.com/talk-about-articles/keyauth-tz/conf"
"gitee.com/talk-about-articles/keyauth-tz/swagger"
)
// NewHTTPService 构建函数
func NewHTTPService() *HTTPService {
r := restful.DefaultContainer
// Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API
// You need to download the Swagger HTML5 assets and change the FilePath location in the config below.
// Open http://localhost:8080/apidocs/?url=http://localhost:8080/apidocs.json
// http.Handle("/apidocs/", http.StripPrefix("/apidocs/", http.FileServer(http.Dir("/Users/emicklei/Projects/swagger-ui/dist"))))
// Optionally, you may need to enable CORS for the UI to work.
cors := restful.CrossOriginResourceSharing{
AllowedHeaders: []string{"*"},
AllowedMethods: []string{"*"},
CookiesAllowed: false,
Container: r}
r.Filter(cors.Filter)
server := &http.Server{
ReadHeaderTimeout: 60 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20, // 1M
Addr: conf.C().App.HTTP.Addr(),
Handler: r,
}
return &HTTPService{
r: r,
server: server,
l: zap.L().Named("HTTP Service"),
c: conf.C(),
}
}
// HTTPService http服务
type HTTPService struct {
r *restful.Container
l logger.Logger
c *conf.Config
server *http.Server
}
func (s *HTTPService) PathPrefix() string {
return fmt.Sprintf("/%s/api", s.c.App.Name)
}
// Start 启动服务
func (s *HTTPService) Start() error {
// 装置子服务路由
app.LoadRESTfulApp(s.PathPrefix(), s.r)
// API Doc
config := restfulspec.Config{
WebServices: restful.RegisteredWebServices(), // you control what services are visible
APIPath: "/apidocs.json",
PostBuildSwaggerObjectHandler: swagger.Docs}
s.r.Add(restfulspec.NewOpenAPIService(config))
s.l.Infof("Get the API using http://%s%s", s.c.App.HTTP.Addr(), config.APIPath)
// 启动 HTTP服务
s.l.Infof("HTTP服务启动成功, 监听地址: %s", s.server.Addr)
if err := s.server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
s.l.Info("service is stopped")
}
return fmt.Errorf("start service error, %s", err.Error())
}
return nil
}
// Stop 停止server
func (s *HTTPService) Stop() error {
s.l.Info("start graceful shutdown")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// 优雅关闭HTTP服务
if err := s.server.Shutdown(ctx); err != nil {
s.l.Errorf("graceful shutdown timeout, force exit")
}
return nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/talk-about-articles/keyauth-tz.git
git@gitee.com:talk-about-articles/keyauth-tz.git
talk-about-articles
keyauth-tz
keyauth-tz
v1.0.14

搜索帮助