加入summary 优化http监听逻辑,实现基本身份认证

This commit is contained in:
dexter
2022-03-01 20:42:25 +08:00
parent 37586d4a0b
commit abe2cdd1fc
11 changed files with 326 additions and 64 deletions

View File

@@ -4,27 +4,69 @@ import (
"context"
"net/http"
. "github.com/logrusorgru/aurora"
"golang.org/x/sync/errgroup"
"m7s.live/engine/v4/log"
"m7s.live/engine/v4/util"
)
var _ HTTPConfig = (*HTTP)(nil)
type HTTP struct {
ListenAddr string
ListenAddrTLS string
CertFile string
KeyFile string
CORS bool //是否自动添加CORS头
UserName string
Password string
mux *http.ServeMux
}
type HTTPConfig interface {
InitMux()
GetHTTPConfig() *HTTP
Listen(ctx context.Context) error
HandleFunc(string, func(http.ResponseWriter, *http.Request))
}
func (config *HTTP) InitMux() {
hasOwnTLS := config.ListenAddrTLS != "" && config.ListenAddrTLS != Global.ListenAddrTLS
hasOwnHTTP := config.ListenAddr != "" && config.ListenAddr != Global.ListenAddr
if hasOwnTLS || hasOwnHTTP {
config.mux = http.NewServeMux()
}
}
func (config *HTTP) HandleFunc(path string, f func(http.ResponseWriter, *http.Request)) {
if config.mux != nil {
if config.CORS {
f = util.CORS(f)
}
if config.UserName != "" && config.Password != "" {
f = util.BasicAuth(config.UserName, config.Password, f)
}
config.mux.HandleFunc(path, f)
}
}
func (config *HTTP) GetHTTPConfig() *HTTP {
return config
}
// ListenAddrs Listen http and https
func (config *HTTP) Listen(ctx context.Context, plugin HTTPPlugin) error {
func (config *HTTP) Listen(ctx context.Context) error {
var g errgroup.Group
if config.ListenAddrTLS != "" {
if config.ListenAddrTLS != "" && (config == &Global.HTTP || config.ListenAddrTLS != Global.ListenAddrTLS) {
g.Go(func() error {
return http.ListenAndServeTLS(config.ListenAddrTLS, config.CertFile, config.KeyFile, plugin)
log.Info("🌐 https listen at ", Blink(config.ListenAddrTLS))
return http.ListenAndServeTLS(config.ListenAddrTLS, config.CertFile, config.KeyFile, config.mux)
})
}
if config.ListenAddr != "" {
g.Go(func() error { return http.ListenAndServe(config.ListenAddr, plugin) })
if config.ListenAddr != "" && (config == &Global.HTTP || config.ListenAddr != Global.ListenAddr) {
g.Go(func() error {
log.Info("🌐 http listen at ", Blink(config.ListenAddr))
return http.ListenAndServe(config.ListenAddr, config.mux)
})
}
g.Go(func() error {
<-ctx.Done()