62 Star 345 Fork 417

infraboard / go-course

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
http.go 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
Mr.Yu 提交于 2021-09-01 21:49 . 添加工程化
package protocol
import (
"context"
"fmt"
"net/http"
"time"
"github.com/infraboard/mcube/logger"
"github.com/infraboard/mcube/logger/zap"
"github.com/julienschmidt/httprouter"
"github.com/rs/cors"
"gitee.com/infraboard/go-course/day14/demo/api/conf"
hostAPI "gitee.com/infraboard/go-course/day14/demo/api/pkg/host/http"
)
// NewHTTPService 构建函数
func NewHTTPService() *HTTPService {
r := httprouter.New()
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.Addr(),
Handler: cors.AllowAll().Handler(r),
}
return &HTTPService{
r: r,
server: server,
l: zap.L().Named("API"),
c: conf.C(),
}
}
// HTTPService http服务
type HTTPService struct {
r *httprouter.Router
l logger.Logger
c *conf.Config
server *http.Server
}
// Start 启动服务
func (s *HTTPService) Start() error {
// 装置子服务路由
hostAPI.RegistAPI(s.r)
// 启动 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
}
Go
1
https://gitee.com/infraboard/go-course.git
git@gitee.com:infraboard/go-course.git
infraboard
go-course
go-course
19a3f401ff21

搜索帮助