-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
64 lines (54 loc) · 1.72 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
type Config struct {
Username string `json:"username"`
Cookie string `json:"cookie"`
}
func LoadConfig(filePath string) (*Config, error) {
if _, err := os.Stat(filePath); os.IsNotExist(err) {
// Create the config directory if it doesn't exist
configDir := filepath.Dir(filePath)
err = os.MkdirAll(configDir, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("error creating config directory: %v", err)
}
// Create a blank config file
blankConfig := &Config{
Username: "",
Cookie: "",
}
file, err := os.Create(filePath)
if err != nil {
return nil, fmt.Errorf("error creating config file: %v", err)
}
defer file.Close()
encoder := json.NewEncoder(file)
err = encoder.Encode(blankConfig)
if err != nil {
return nil, fmt.Errorf("error encoding blank config: %v", err)
}
fmt.Printf("Config file not found. A blank config has been created at %s\n", filePath)
fmt.Println("Please edit the config file and provide the necessary values.")
os.Exit(1)
}
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("error opening config file: %v", err)
}
defer file.Close()
var config Config
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if err != nil {
return nil, fmt.Errorf("error decoding config file: %v", err)
}
if config.Username == "" || config.Cookie == "" {
return nil, fmt.Errorf("missing required config values")
}
return &config, nil
}