From 651653256815473653aba0f11a12959461474221 Mon Sep 17 00:00:00 2001 From: David Wen Riccardi-Zhu Date: Thu, 16 Oct 2025 02:29:02 +0000 Subject: [PATCH] Add optional TLS support (#340) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add optional TLS support Introduce HTTPS support with net/http Server.ListenAndServeTLS. This should enable the option of serving via HTTPS without a reverse proxy. Add two flags: - tls-cert-file (path to the TLS certificate file) - tls-key-file (path to the TLS private key file) Both flags must be supplied together; otherwise exit with error. If both flags are present, call srv.ListenAndServeTLS. If not, fall back to the existing srv.ListenAndServe (HTTP); no changes to existing non‑TLS behavior. --- llama-swap.go | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/llama-swap.go b/llama-swap.go index bf93a41..95fb67c 100644 --- a/llama-swap.go +++ b/llama-swap.go @@ -28,7 +28,9 @@ var ( func main() { // Define a command-line flag for the port configPath := flag.String("config", "config.yaml", "config file name") - listenStr := flag.String("listen", ":8080", "listen ip/port") + listenStr := flag.String("listen", "", "listen ip/port") + certFile := flag.String("tls-cert-file", "", "TLS certificate file") + keyFile := flag.String("tls-key-file", "", "TLS key file") showVersion := flag.Bool("version", false, "show version of build") watchConfig := flag.Bool("watch-config", false, "Automatically reload config file on change") @@ -55,6 +57,23 @@ func main() { gin.SetMode(gin.ReleaseMode) } + // Validate TLS flags. + var useTLS = (*certFile != "" && *keyFile != "") + if (*certFile != "" && *keyFile == "") || + (*certFile == "" && *keyFile != "") { + fmt.Println("Error: Both --tls-cert-file and --tls-key-file must be provided for TLS.") + os.Exit(1) + } + + // Set default ports. + if *listenStr == "" { + defaultPort := ":8080" + if useTLS { + defaultPort = ":8443" + } + listenStr = &defaultPort + } + // Setup channels for server management exitChan := make(chan struct{}) sigChan := make(chan os.Signal, 1) @@ -167,9 +186,16 @@ func main() { }() // Start server - fmt.Printf("llama-swap listening on %s\n", *listenStr) go func() { - if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + var err error + if useTLS { + fmt.Printf("llama-swap listening with TLS on https://%s\n", *listenStr) + err = srv.ListenAndServeTLS(*certFile, *keyFile) + } else { + fmt.Printf("llama-swap listening on http://%s\n", *listenStr) + err = srv.ListenAndServe() + } + if err != nil && err != http.ErrServerClosed { log.Fatalf("Fatal server error: %v\n", err) } }()