Improve [Startup Server] Support TLS

- [+] feat(init.go): add TLS certificate and key command line flags
- [+] feat(main.go): implement TLS support for the server with fallback to environment variables
- [+] fix(main.go): improve logging messages for server start and error handling
This commit is contained in:
H0llyW00dzZ 2025-04-14 00:29:07 +07:00
parent 8df4a2670b
commit 1168c326c7
No known key found for this signature in database
GPG Key ID: A0F9424A7002343A
2 changed files with 29 additions and 6 deletions

View File

@ -3,11 +3,12 @@ package common
import (
"flag"
"fmt"
"github.com/songquanpeng/one-api/common/config"
"github.com/songquanpeng/one-api/common/logger"
"log"
"os"
"path/filepath"
"github.com/songquanpeng/one-api/common/config"
"github.com/songquanpeng/one-api/common/logger"
)
var (
@ -15,13 +16,15 @@ var (
PrintVersion = flag.Bool("version", false, "print version and exit")
PrintHelp = flag.Bool("help", false, "print help and exit")
LogDir = flag.String("log-dir", "./logs", "specify the log directory")
TLSCertFile = flag.String("tls-cert", "", "path to TLS certificate file")
TLSKeyFile = flag.String("tls-key", "", "path to TLS key file")
)
func printHelp() {
fmt.Println("One API " + Version + " - All in one API service for OpenAI API.")
fmt.Println("Copyright (C) 2023 JustSong. All rights reserved.")
fmt.Println("GitHub: https://github.com/songquanpeng/one-api")
fmt.Println("Usage: one-api [--port <port>] [--log-dir <log directory>] [--version] [--help]")
fmt.Println("Usage: one-api [--port <port>] [--log-dir <log directory>] [--tls-cert <path>] [--tls-key <path>] [--version] [--help]")
}
func Init() {

22
main.go
View File

@ -116,9 +116,29 @@ func main() {
if port == "" {
port = strconv.Itoa(*common.Port)
}
// Check for TLS configuration - prioritize command line flags over environment variables
certFile := *common.TLSCertFile
keyFile := *common.TLSKeyFile
// If flags are not set, fallback to environment variables
if certFile == "" {
certFile = os.Getenv("TLS_CERT_FILE")
}
if keyFile == "" {
keyFile = os.Getenv("TLS_KEY_FILE")
}
// Start the server with or without TLS
if certFile != "" && keyFile != "" {
logger.SysLogf("server started with TLS on https://localhost:%s", port)
err = server.RunTLS(":"+port, certFile, keyFile)
} else {
logger.SysLogf("server started on http://localhost:%s", port)
err = server.Run(":" + port)
}
if err != nil {
logger.FatalLog("failed to start HTTP server: " + err.Error())
logger.FatalLog("failed to start server: " + err.Error())
}
}