From 37df78e5d2c332315ab02b78eeb84b935d23d309 Mon Sep 17 00:00:00 2001 From: wonder Date: Mon, 13 Apr 2026 14:36:54 +0800 Subject: [PATCH] =?UTF-8?q?Refactor:=20=E7=BB=9F=E4=B8=80=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/config/config.go | 88 ++++++++++++++++++++++++++++++++++++ backend/main.go | 31 +++++-------- backend/neo4j/client.go | 53 +++++++--------------- backend/neo4j/client_test.go | 21 +++++++-- 4 files changed, 133 insertions(+), 60 deletions(-) create mode 100644 backend/config/config.go diff --git a/backend/config/config.go b/backend/config/config.go new file mode 100644 index 0000000..ef3d70a --- /dev/null +++ b/backend/config/config.go @@ -0,0 +1,88 @@ +package config + +import ( + "fmt" + "os" + "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 Config struct { + Server ServerConfig + Neo4j Neo4jConfig + Data DataConfig + CORS CORSConfig +} + +func Load() (*Config, error) { + if err := godotenv.Load("../config/.env"); err != nil { + return nil, fmt.Errorf("error loading .env file: %w", err) + } + + 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, + }, + } + + 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 +} diff --git a/backend/main.go b/backend/main.go index 4d96106..80b827c 100644 --- a/backend/main.go +++ b/backend/main.go @@ -1,4 +1,4 @@ -package neo4j +package main import ( "log" @@ -7,18 +7,18 @@ import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" + "knowledge-graph-backend/config" "knowledge-graph-backend/handlers" "knowledge-graph-backend/services" ) -const ( - PORT = "3001" - DATA_FILE = "data.json" -) +func main() { + cfg, err := config.Load() + if err != nil { + log.Fatalf("Failed to load config: %v", err) + } -func test() { - - dataService, err := services.NewDataService(DATA_FILE) + dataService, err := services.NewDataService(cfg.Data.FilePath) if err != nil { log.Fatalf("Failed to initialize data service: %v", err) } @@ -29,14 +29,7 @@ func test() { router := gin.Default() - router.Use(cors.New(cors.Config{ - 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 * 3600, - })) + router.Use(cors.New(cfg.CORS.ToGinConfig())) router.GET("/health", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ @@ -57,8 +50,8 @@ func test() { api.GET("/nodes/:id/neighbors", nodeHandler.GetNeighbors) } - log.Println("Knowledge Graph API Server running on http://localhost:" + PORT) - log.Println("Data file loaded from: " + DATA_FILE) + log.Println("Knowledge Graph API Server running on http://localhost:" + cfg.Server.Port) + log.Println("Data file loaded from: " + cfg.Data.FilePath) log.Println("Available endpoints:") log.Println(" GET /health - Health check") log.Println(" GET /api/graph - Get all graph data") @@ -67,7 +60,7 @@ func test() { log.Println(" GET /api/nodes/:id - Get node by ID") log.Println(" GET /api/nodes/:id/neighbors - Get node neighbors") - if err := router.Run(":" + PORT); err != nil { + if err := router.Run(":" + cfg.Server.Port); err != nil { log.Fatalf("Failed to start server: %v", err) } } diff --git a/backend/neo4j/client.go b/backend/neo4j/client.go index 3b9c28c..b48f5a7 100644 --- a/backend/neo4j/client.go +++ b/backend/neo4j/client.go @@ -3,46 +3,25 @@ package neo4j import ( "context" "fmt" - "log" - "os" - "github.com/joho/godotenv" "github.com/neo4j/neo4j-go-driver/v5/neo4j" + + "knowledge-graph-backend/config" ) -var ( - NEO4J_URI string - NEO4J_USERNAME string - NEO4J_PASSWORD string -) +func DoConnect(cfg config.Neo4jConfig) { + ctx := context.Background() + driver, err := neo4j.NewDriverWithContext( + cfg.URI, + neo4j.BasicAuth(cfg.Username, cfg.Password, "")) + if err != nil { + panic(err) + } + defer driver.Close(ctx) -func init() { - err := godotenv.Load() - if err != nil { - log.Fatal("Error loading .env file") - } - - NEO4J_URI = os.Getenv("NEO4J_URI") - NEO4J_USERNAME = os.Getenv("NEO4J_USERNAME") - NEO4J_PASSWORD = os.Getenv("NEO4J_PASSWORD") -} - -func doConnect() { - ctx := context.Background() - // dbUri := "" - // dbUser := "" - // dbPassword := "" - driver, err := neo4j.NewDriverWithContext( - NEO4J_URI, - neo4j.BasicAuth(NEO4J_USERNAME, NEO4J_PASSWORD, "")) - if err != nil { - panic(err) - } - defer driver.Close(ctx) - - err = driver.VerifyConnectivity(ctx) - if err != nil { - panic(err) - } - fmt.Println("Connection established.") + err = driver.VerifyConnectivity(ctx) + if err != nil { + panic(err) + } + fmt.Println("Connection established.") } diff --git a/backend/neo4j/client_test.go b/backend/neo4j/client_test.go index 651b49d..4f91296 100644 --- a/backend/neo4j/client_test.go +++ b/backend/neo4j/client_test.go @@ -1,7 +1,20 @@ package neo4j -import "testing" +import ( + "testing" -func TestDoConnect(t *testing.T){ - doConnect() -} \ No newline at end of file + "knowledge-graph-backend/config" +) + +func TestDoConnect(t *testing.T) { + cnf, err := config.Load() + if err != nil { + t.Errorf("[cnf]: %v", err) + } + cfg := config.Neo4jConfig{ + URI: cnf.Neo4j.URI, + Username: cnf.Neo4j.Username, + Password: cnf.Neo4j.Password, + } + DoConnect(cfg) +}