github.com/infraboard/keyauth@v0.8.1/protocol/http.go (about)

     1  package protocol
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"time"
     8  
     9  	"github.com/infraboard/mcube/app"
    10  	"github.com/infraboard/mcube/http/middleware/accesslog"
    11  	"github.com/infraboard/mcube/http/middleware/cors"
    12  	"github.com/infraboard/mcube/http/middleware/recovery"
    13  	"github.com/infraboard/mcube/http/router"
    14  	"github.com/infraboard/mcube/http/router/httprouter"
    15  	"github.com/infraboard/mcube/logger"
    16  	"github.com/infraboard/mcube/logger/zap"
    17  
    18  	auther "github.com/infraboard/keyauth/common/interceptor/http"
    19  	"github.com/infraboard/keyauth/conf"
    20  )
    21  
    22  // NewHTTPService 构建函数
    23  func NewHTTPService() *HTTPService {
    24  	r := httprouter.New()
    25  	r.Use(recovery.NewWithLogger(zap.L().Named("Recovery")))
    26  	r.Use(accesslog.NewWithLogger(zap.L().Named("AccessLog")))
    27  	r.Use(cors.AllowAll())
    28  	r.EnableAPIRoot()
    29  	r.SetAuther(auther.NewHTTPAuther())
    30  	r.Auth(true)
    31  	r.Permission(true)
    32  
    33  	server := &http.Server{
    34  		ReadHeaderTimeout: 20 * time.Second,
    35  		ReadTimeout:       20 * time.Second,
    36  		WriteTimeout:      25 * time.Second,
    37  		IdleTimeout:       120 * time.Second,
    38  		MaxHeaderBytes:    1 << 20,
    39  		Addr:              conf.C().App.HTTPAddr(),
    40  		Handler:           r,
    41  	}
    42  
    43  	return &HTTPService{
    44  		r:      r,
    45  		server: server,
    46  		l:      zap.L().Named("HTTP Service"),
    47  		c:      conf.C(),
    48  	}
    49  }
    50  
    51  // HTTPService http服务
    52  type HTTPService struct {
    53  	r      router.Router
    54  	l      logger.Logger
    55  	c      *conf.Config
    56  	server *http.Server
    57  }
    58  
    59  func (s *HTTPService) PathPrefix() string {
    60  	return fmt.Sprintf("/%s/api/v1", s.c.App.Name)
    61  }
    62  
    63  // Start 启动服务
    64  func (s *HTTPService) Start() error {
    65  	// 装置子服务路由
    66  	app.LoadHttpApp(s.PathPrefix(), s.r)
    67  
    68  	// 启动HTTP服务
    69  	s.l.Infof("HTTP 服务开始启动, 监听地址: %s", s.server.Addr)
    70  	if err := s.server.ListenAndServe(); err != nil {
    71  		if err == http.ErrServerClosed {
    72  			s.l.Info("service is stopped")
    73  		}
    74  		return fmt.Errorf("start service error, %s", err.Error())
    75  	}
    76  	return nil
    77  }
    78  
    79  // Stop 停止server
    80  func (s *HTTPService) Stop() error {
    81  	s.l.Info("start http graceful shutdown ...")
    82  
    83  	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    84  	defer cancel()
    85  
    86  	// 优雅关闭HTTP服务
    87  	if err := s.server.Shutdown(ctx); err != nil {
    88  		s.l.Errorf("graceful shutdown timeout, force exit")
    89  	}
    90  
    91  	return nil
    92  }