Skip to content

Commit 6516532

Browse files
authored
Add optional TLS support (#340)
* 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.
1 parent d58a8b8 commit 6516532

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

llama-swap.go

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ var (
2828
func main() {
2929
// Define a command-line flag for the port
3030
configPath := flag.String("config", "config.yaml", "config file name")
31-
listenStr := flag.String("listen", ":8080", "listen ip/port")
31+
listenStr := flag.String("listen", "", "listen ip/port")
32+
certFile := flag.String("tls-cert-file", "", "TLS certificate file")
33+
keyFile := flag.String("tls-key-file", "", "TLS key file")
3234
showVersion := flag.Bool("version", false, "show version of build")
3335
watchConfig := flag.Bool("watch-config", false, "Automatically reload config file on change")
3436

@@ -55,6 +57,23 @@ func main() {
5557
gin.SetMode(gin.ReleaseMode)
5658
}
5759

60+
// Validate TLS flags.
61+
var useTLS = (*certFile != "" && *keyFile != "")
62+
if (*certFile != "" && *keyFile == "") ||
63+
(*certFile == "" && *keyFile != "") {
64+
fmt.Println("Error: Both --tls-cert-file and --tls-key-file must be provided for TLS.")
65+
os.Exit(1)
66+
}
67+
68+
// Set default ports.
69+
if *listenStr == "" {
70+
defaultPort := ":8080"
71+
if useTLS {
72+
defaultPort = ":8443"
73+
}
74+
listenStr = &defaultPort
75+
}
76+
5877
// Setup channels for server management
5978
exitChan := make(chan struct{})
6079
sigChan := make(chan os.Signal, 1)
@@ -167,9 +186,16 @@ func main() {
167186
}()
168187

169188
// Start server
170-
fmt.Printf("llama-swap listening on %s\n", *listenStr)
171189
go func() {
172-
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
190+
var err error
191+
if useTLS {
192+
fmt.Printf("llama-swap listening with TLS on https://%s\n", *listenStr)
193+
err = srv.ListenAndServeTLS(*certFile, *keyFile)
194+
} else {
195+
fmt.Printf("llama-swap listening on http://%s\n", *listenStr)
196+
err = srv.ListenAndServe()
197+
}
198+
if err != nil && err != http.ErrServerClosed {
173199
log.Fatalf("Fatal server error: %v\n", err)
174200
}
175201
}()

0 commit comments

Comments
 (0)