feat: add quicConfig

This commit is contained in:
langhuihui
2023-09-12 12:40:07 +08:00
parent 5215233937
commit 148768d9fc
5 changed files with 90 additions and 18 deletions
+6
View File
@@ -9,6 +9,7 @@ import (
"strings"
"time"
"github.com/quic-go/quic-go"
"gopkg.in/yaml.v3"
"m7s.live/engine/v4/log"
)
@@ -32,6 +33,11 @@ type HTTPPlugin interface {
http.Handler
}
type QuicPlugin interface {
Plugin
ServeQuic(quic.Connection)
}
// CreateElem 创建Map或者Slice中的元素
func (config Config) CreateElem(eleType reflect.Type) reflect.Value {
if eleType.Kind() == reflect.Pointer {
+68
View File
@@ -0,0 +1,68 @@
package config
import (
"context"
"crypto/tls"
"github.com/quic-go/quic-go"
"m7s.live/engine/v4/log"
)
type QuicConfig interface {
ListenQuic(context.Context, QuicPlugin) error
}
type Quic struct {
ListenAddr string
CertFile string
KeyFile string
}
func (q *Quic) ListenQuic(ctx context.Context, plugin QuicPlugin) error {
listener, err := quic.ListenAddr(q.ListenAddr, q.generateTLSConfig(), &quic.Config{
EnableDatagrams: true,
})
if err != nil {
return err
}
log.Infof("quic listen at %s", q.ListenAddr)
for {
conn, err := listener.Accept(ctx)
if err != nil {
return err
}
go plugin.ServeQuic(conn)
}
}
func (q *Quic) generateTLSConfig() *tls.Config {
// key, err := rsa.GenerateKey(rand.Reader, 1024)
// if err != nil {
// panic(err)
// }
// template := x509.Certificate{SerialNumber: big.NewInt(1)}
// certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
// if err != nil {
// panic(err)
// }
// keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
// certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
// tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
keyPair, err := tls.X509KeyPair(LocalCert, LocalKey)
if q.CertFile != "" || q.KeyFile != "" {
keyPair, err = tls.LoadX509KeyPair(q.CertFile, q.KeyFile)
}
if err != nil {
if Global.LogLang == "zh" {
log.Fatalf("加载证书失败: %v", err)
} else {
log.Fatalf("LoadX509KeyPair error: %v", err)
}
panic(err)
}
return &tls.Config{
Certificates: []tls.Certificate{keyPair},
NextProtos: []string{"monibuca"},
}
}