Files
knowledge-graph-agent/backend/internal/config/config.go
T

125 lines
2.5 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
"runtime"
"time"
"github.com/gin-contrib/cors"
"github.com/joho/godotenv"
)
type ServerConfig struct {
Port string
}
type Neo4jConfig struct {
URI string
Username string
Password string
}
type DataConfig struct {
FilePath string
}
type CORSConfig struct {
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge time.Duration
}
type LLMConfig struct {
Provider string
APIKey string
Model string
BaseURL string
}
type Config struct {
Server ServerConfig
Neo4j Neo4jConfig
Data DataConfig
CORS CORSConfig
LLM LLMConfig
}
func Load() (*Config, error) {
// 查找go.mod所在的模块根目录
_, filename, _, ok := runtime.Caller(0)
if !ok {
return nil, fmt.Errorf("unable to get caller info")
}
dir := filepath.Dir(filename)
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
// 找到模块根目录,加载configs/.env
envPath := filepath.Join(dir, "configs", ".env")
if err = godotenv.Load(envPath); err == nil {
break
}
}
parent := filepath.Dir(dir)
if parent == dir {
break
}
dir = parent
}
// 如果找不到.env,继续使用环境变量
cfg := &Config{
Server: ServerConfig{
Port: getEnv("PORT", "3001"),
},
Neo4j: Neo4jConfig{
URI: os.Getenv("NEO4J_URI"),
Username: os.Getenv("NEO4J_USERNAME"),
Password: os.Getenv("NEO4J_PASSWORD"),
},
Data: DataConfig{
FilePath: getEnv("DATA_FILE", "data.json"),
},
CORS: CORSConfig{
AllowOrigins: []string{"http://localhost:5173", "http://localhost:3000"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization", "Accept"},
ExposeHeaders: []string{"Content-Length", "Content-Type"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
},
LLM: LLMConfig{
Provider: os.Getenv("PROVIDER"),
APIKey: os.Getenv("API_KEY"),
Model: os.Getenv("MODEL"),
BaseURL: os.Getenv("BASE_URL"),
},
}
return cfg, nil
}
func (c *CORSConfig) ToGinConfig() cors.Config {
return cors.Config{
AllowOrigins: c.AllowOrigins,
AllowMethods: c.AllowMethods,
AllowHeaders: c.AllowHeaders,
ExposeHeaders: c.ExposeHeaders,
AllowCredentials: c.AllowCredentials,
MaxAge: c.MaxAge,
}
}
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}