From 8f760582e04b8264333fd0d7d2dc0b36d3d8a756 Mon Sep 17 00:00:00 2001 From: Merith-TK Date: Tue, 4 Feb 2025 17:17:16 +0000 Subject: [PATCH] default config options --- config.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/config.go b/config.go index 4ec682e..590e0c9 100644 --- a/config.go +++ b/config.go @@ -17,7 +17,23 @@ type Proxy struct { Type string `json:"type,omitempty"` // "tcp", "udp", or "both" } +// ReadConfig loads the configuration or generates a default one if missing. func ReadConfig(configPath string) ProxyConfig { + if _, err := os.Stat(configPath); os.IsNotExist(err) { + log.Printf("[INFO] Config file not found, generating default config at %s\n", configPath) + defaultConfig := ProxyConfig{ + Proxy: []Proxy{ + { + Local: "127.0.0.1:8080", + Remote: "127.0.0.1:8081", + Type: "both", + }, + }, + } + saveConfig(configPath, defaultConfig) + return defaultConfig + } + configData, err := os.ReadFile(configPath) if err != nil { log.Fatalf("[ERROR] Failed to read config file (%s): %v\n", configPath, err) @@ -29,3 +45,15 @@ func ReadConfig(configPath string) ProxyConfig { } return config } + +// saveConfig writes the given configuration to a file. +func saveConfig(configPath string, config ProxyConfig) { + configData, err := json5.MarshalIndent(config, "", " ") + if err != nil { + log.Fatalf("[ERROR] Failed to generate default config: %v\n", err) + } + + if err := os.WriteFile(configPath, configData, 0644); err != nil { + log.Fatalf("[ERROR] Failed to write default config file: %v\n", err) + } +}