Skip to content

Commit fa69368

Browse files
committed
Load config file from home dir
1 parent 6b5d02e commit fa69368

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

common/config.go

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package common
22

33
import (
4+
"fmt"
45
"gopkg.in/yaml.v3"
56
"os"
67
"path"
@@ -28,15 +29,44 @@ func getConfigPath(isServer bool) string {
2829
} else {
2930
configPath = path.Join(*ConfigPath, "go-public-client.yaml")
3031
}
32+
// If config file is not found in the specified path, try to find it in the default path
33+
if _, err := os.Stat(*ConfigPath); os.IsNotExist(err) {
34+
basePath := path.Join(GetHomeDir(), ".config")
35+
var configPath2 string
36+
if isServer {
37+
configPath2 = path.Join(basePath, "go-public-server.yaml")
38+
} else {
39+
configPath2 = path.Join(basePath, "go-public-client.yaml")
40+
}
41+
if _, err := os.Stat(configPath2); err == nil {
42+
configPath = configPath2
43+
}
44+
}
3145
return configPath
3246
}
3347

3448
func InitConfigFile(isServer bool) {
3549
configPath := getConfigPath(isServer)
3650
if _, err := os.Stat(configPath); err == nil {
37-
println("Config file already exists.")
51+
fmt.Println("Config file already exists at: " + configPath)
3852
os.Exit(1)
3953
}
54+
if !isServer {
55+
fmt.Print("Where do you want to save the config file? (default: ~/.config) ")
56+
var input string
57+
_, _ = fmt.Scanln(&input)
58+
if input == "" {
59+
input = path.Join(GetHomeDir(), ".config")
60+
}
61+
if _, err := os.Stat(input); os.IsNotExist(err) {
62+
err := os.Mkdir(input, 0700)
63+
if err != nil {
64+
fmt.Println("Failed to create directory: " + input)
65+
os.Exit(1)
66+
}
67+
}
68+
configPath = path.Join(input, "go-public-client.yaml")
69+
}
4070
defaultServerConfig := serverConfig{
4171
Port: 6871,
4272
Token: GenerateToken(),

common/utils.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package common
22

33
import (
44
"github.com/google/uuid"
5+
"os/user"
56
)
67

78
func GenerateToken() string {
@@ -24,3 +25,8 @@ func Bytes2Token(bytes []byte) string {
2425
}
2526
return id.String()
2627
}
28+
29+
func GetHomeDir() string {
30+
usr, _ := user.Current()
31+
return usr.HomeDir
32+
}

0 commit comments

Comments
 (0)