http.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package config
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "net/http"
  6. "time"
  7. "encoding/hex"
  8. "fmt"
  9. "crypto/md5"
  10. "github.com/logrusorgru/aurora/v4"
  11. "golang.org/x/sync/errgroup"
  12. "m7s.live/engine/v4/log"
  13. "m7s.live/engine/v4/util"
  14. )
  15. var _ HTTPConfig = (*HTTP)(nil)
  16. type Middleware func(string, http.Handler) http.Handler
  17. type HTTP struct {
  18. ListenAddr string `desc:"监听地址"`
  19. ListenAddrTLS string `desc:"监听地址HTTPS"`
  20. CertFile string `desc:"HTTPS证书文件"`
  21. KeyFile string `desc:"HTTPS密钥文件"`
  22. CORS bool `default:"true" desc:"是否自动添加CORS头"` //是否自动添加CORS头
  23. UserName string `desc:"基本身份认证用户名"`
  24. Password string `desc:"基本身份认证密码"`
  25. ReadTimeout time.Duration `desc:"读取超时"`
  26. WriteTimeout time.Duration `desc:"写入超时"`
  27. IdleTimeout time.Duration `desc:"空闲超时"`
  28. mux *http.ServeMux
  29. middlewares []Middleware
  30. AuthKey string
  31. AuthSecret string
  32. }
  33. type HTTPConfig interface {
  34. GetHTTPConfig() *HTTP
  35. Listen(ctx context.Context) error
  36. Handle(string, http.Handler)
  37. Handler(*http.Request) (http.Handler, string)
  38. AddMiddleware(Middleware)
  39. }
  40. func (config *HTTP)AuthMiddleware(){
  41. Global.HTTP.AddMiddleware(func(pattern string, handler http.Handler) http.Handler {
  42. return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  43. if config.AuthKey != ""{
  44. m := md5.New()
  45. m.Write([]byte(config.AuthKey+config.AuthSecret+config.AuthSecret+config.AuthKey))
  46. signStr := hex.EncodeToString(m.Sum(nil))
  47. sign := r.URL.Query().Get("sign")
  48. if sign != signStr{
  49. http.Error(rw, fmt.Errorf("签名未通过").Error(), http.StatusBadRequest)
  50. return
  51. }
  52. }
  53. handler.ServeHTTP(rw, r)
  54. })
  55. })
  56. }
  57. func (config *HTTP) AddMiddleware(middleware Middleware) {
  58. //fmt.Println("add AddMiddleware xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",)
  59. config.middlewares = append(config.middlewares, middleware)
  60. }
  61. func (config *HTTP) Handle(path string, f http.Handler) {
  62. if config.mux == nil {
  63. config.mux = http.NewServeMux()
  64. }
  65. if config.CORS {
  66. f = util.CORS(f)
  67. }
  68. if config.UserName != "" && config.Password != "" {
  69. f = util.BasicAuth(config.UserName, config.Password, f)
  70. }
  71. for _, middleware := range config.middlewares {
  72. f = middleware(path, f)
  73. }
  74. config.mux.Handle(path, f)
  75. }
  76. func (config *HTTP) GetHTTPConfig() *HTTP {
  77. return config
  78. }
  79. func (config *HTTP) Handler(r *http.Request) (h http.Handler, pattern string) {
  80. //fmt.Println("HANDLER111111111111111111111111111111:",r.RequestURI,r.Method)
  81. return config.mux.Handler(r)
  82. }
  83. // ListenAddrs Listen http and https
  84. func (config *HTTP) Listen(ctx context.Context) error {
  85. if config.mux == nil {
  86. return nil
  87. }
  88. //fmt.Println("LISTEN 1111111111111111111111111111111111111111111111111 START",*config)
  89. var g errgroup.Group
  90. if config.ListenAddrTLS != "" && (config == &Global.HTTP || config.ListenAddrTLS != Global.ListenAddrTLS) {
  91. g.Go(func() error {
  92. if Global.LogLang == "zh" {
  93. log.Info("🌐 https 监听在 ", aurora.Blink(config.ListenAddrTLS))
  94. } else {
  95. log.Info("🌐 https listen at ", aurora.Blink(config.ListenAddrTLS))
  96. }
  97. cer, _ := tls.X509KeyPair(LocalCert, LocalKey)
  98. var server = http.Server{
  99. Addr: config.ListenAddrTLS,
  100. ReadTimeout: config.ReadTimeout,
  101. WriteTimeout: config.WriteTimeout,
  102. IdleTimeout: config.IdleTimeout,
  103. Handler: config.mux,
  104. TLSConfig: &tls.Config{
  105. Certificates: []tls.Certificate{cer},
  106. CipherSuites: []uint16{
  107. tls.TLS_AES_128_GCM_SHA256,
  108. tls.TLS_CHACHA20_POLY1305_SHA256,
  109. tls.TLS_AES_256_GCM_SHA384,
  110. //tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  111. //tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  112. //tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
  113. //tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
  114. tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
  115. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  116. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  117. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  118. tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
  119. tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
  120. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
  121. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  122. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
  123. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  124. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
  125. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  126. },
  127. },
  128. }
  129. return server.ListenAndServeTLS(config.CertFile, config.KeyFile)
  130. })
  131. }
  132. //fmt.Println("listen http 11111111111111111111111111111111111", config.ListenAddr,Global.ListenAddr,config == &Global.HTTP)
  133. if config.ListenAddr != "" && (config == &Global.HTTP || config.ListenAddr != Global.ListenAddr) {
  134. g.Go(func() error {
  135. if Global.LogLang == "zh" {
  136. log.Info("🌐 http 监听在 ", aurora.Blink(config.ListenAddr))
  137. } else {
  138. log.Info("🌐 http listen at ", aurora.Blink(config.ListenAddr))
  139. }
  140. var server = http.Server{
  141. Addr: config.ListenAddr,
  142. ReadTimeout: config.ReadTimeout,
  143. WriteTimeout: config.WriteTimeout,
  144. IdleTimeout: config.IdleTimeout,
  145. Handler: config.mux,
  146. }
  147. return server.ListenAndServe()
  148. })
  149. }
  150. g.Go(func() error {
  151. <-ctx.Done()
  152. return ctx.Err()
  153. })
  154. return g.Wait()
  155. }