Refactor: 统一配置类

This commit is contained in:
2026-04-13 14:36:54 +08:00
parent c11dfe985f
commit 37df78e5d2
4 changed files with 133 additions and 60 deletions
+16 -37
View File
@@ -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 := "<database-uri>"
// dbUser := "<username>"
// dbPassword := "<password>"
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.")
}
+17 -4
View File
@@ -1,7 +1,20 @@
package neo4j
import "testing"
import (
"testing"
func TestDoConnect(t *testing.T){
doConnect()
}
"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)
}