代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。