refactor: 按go modules规范重构
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
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) {
|
||||
var err error
|
||||
err = godotenv.Load("../configs/.env")
|
||||
err = godotenv.Load("./configs/.env")
|
||||
if 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
|
||||
}
|
||||
Reference in New Issue
Block a user