69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"git.echol.cn/loser/ai_proxy/server/global"
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// LoadTls 加载 TLS 证书
|
|
func LoadTls() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if global.GVA_CONFIG.System.UseHttps {
|
|
certFile := global.GVA_CONFIG.System.TlsCert
|
|
keyFile := global.GVA_CONFIG.System.TlsKey
|
|
|
|
if certFile == "" || keyFile == "" {
|
|
global.GVA_LOG.Error("TLS cert or key file not configured")
|
|
c.AbortWithStatus(500)
|
|
return
|
|
}
|
|
|
|
// 检查证书文件是否存在
|
|
if _, err := os.Stat(certFile); os.IsNotExist(err) {
|
|
global.GVA_LOG.Error("TLS cert file not found", zap.String("file", certFile))
|
|
c.AbortWithStatus(500)
|
|
return
|
|
}
|
|
|
|
if _, err := os.Stat(keyFile); os.IsNotExist(err) {
|
|
global.GVA_LOG.Error("TLS key file not found", zap.String("file", keyFile))
|
|
c.AbortWithStatus(500)
|
|
return
|
|
}
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// LoadTlsFromFile 从文件加载 TLS 证书内容
|
|
func LoadTlsFromFile(certFile, keyFile string) (certPEM, keyPEM []byte, err error) {
|
|
certF, err := os.Open(certFile)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("open cert file error: %w", err)
|
|
}
|
|
defer certF.Close()
|
|
|
|
keyF, err := os.Open(keyFile)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("open key file error: %w", err)
|
|
}
|
|
defer keyF.Close()
|
|
|
|
certPEM, err = io.ReadAll(certF)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("read cert file error: %w", err)
|
|
}
|
|
|
|
keyPEM, err = io.ReadAll(keyF)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("read key file error: %w", err)
|
|
}
|
|
|
|
return certPEM, keyPEM, nil
|
|
}
|