From 00601ca98255f9b56935a694c609c1a06edb5ff1 Mon Sep 17 00:00:00 2001 From: dagehuifei Date: Sat, 12 Oct 2024 10:14:38 +0800 Subject: [PATCH] feat: Add TLS Cert File flag --- cmd/main.go | 20 ++++++++++++++++++-- examples/tls/main.go | 5 ++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 6b63130a..d20ba690 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -5,6 +5,7 @@ package main import ( + "crypto/tls" "flag" "log" "os" @@ -20,6 +21,8 @@ func main() { tcpAddr := flag.String("tcp", ":1883", "network address for TCP listener") wsAddr := flag.String("ws", ":1882", "network address for Websocket listener") infoAddr := flag.String("info", ":8080", "network address for web info dashboard listener") + tlsCertFile := flag.String("tls-cert-file", "", "TLS certificate file") + tlsKeyFile := flag.String("tls-key-file", "", "TLS key file") flag.Parse() sigs := make(chan os.Signal, 1) @@ -30,12 +33,25 @@ func main() { done <- true }() + var tlsConfig *tls.Config + + if tlsCertFile != nil && tlsKeyFile != nil && *tlsCertFile != "" && *tlsKeyFile != "" { + cert, err := tls.LoadX509KeyPair(*tlsCertFile, *tlsKeyFile) + if err != nil { + return + } + tlsConfig = &tls.Config{ + Certificates: []tls.Certificate{cert}, + } + } + server := mqtt.New(nil) _ = server.AddHook(new(auth.AllowHook), nil) tcp := listeners.NewTCP(listeners.Config{ - ID: "t1", - Address: *tcpAddr, + ID: "t1", + Address: *tcpAddr, + TLSConfig: tlsConfig, }) err := server.AddListener(tcp) if err != nil { diff --git a/examples/tls/main.go b/examples/tls/main.go index 26d89a7c..e5844345 100644 --- a/examples/tls/main.go +++ b/examples/tls/main.go @@ -57,7 +57,10 @@ func main() { done <- true }() - cert, err := tls.X509KeyPair(testCertificate, testPrivateKey) + // Load tls cert from your cert file + cert, err := tls.LoadX509KeyPair("replace_your_cert.pem", "replace_your_cert.key") + + //cert, err := tls.X509KeyPair(testCertificate, testPrivateKey) if err != nil { log.Fatal(err) }