-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
86 lines (71 loc) · 1.68 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
"strings"
)
type Config struct {
APIKey string
}
func getOrCreateAPIKey() string {
apiKey := os.Getenv("NASA_API_KEY")
if apiKey != "" {
return apiKey
}
filePathName := "Keys.json"
config, err := readConfig(filePathName)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("API key not found in Keys.json")
fmt.Println("Please sign up for an API key at https://api.nasa.gov/#signUp")
fmt.Println("Once you have your API key, enter it below:")
reader := bufio.NewReader(os.Stdin)
apiKey, err := reader.ReadString('\n')
if err != nil {
log.Fatalf("Error reading API key input: %v", err)
}
apiKey = strings.TrimSpace(apiKey)
config := &Config{APIKey: apiKey}
err = writeConfig("Keys.json", config)
if err != nil {
log.Fatalf("Error saving API key to file: %v", err)
}
fmt.Printf("API key saved to %s.\n", filePathName)
return apiKey
}
log.Fatalf("Error reading Keys.json: %v", err)
}
apiKey = config.APIKey
return apiKey
}
// Reads the configuration data from a file.
func readConfig(fileName string) (*Config, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer file.Close()
config := &Config{}
err = json.NewDecoder(file).Decode(config)
if err != nil {
fmt.Printf("Error decoding config file: %v\n", err)
return nil, err
}
return config, nil
}
// Saves the configuration data to a file.
func writeConfig(fileName string, config *Config) error {
file, err := os.Create(fileName)
if err != nil {
return err
}
defer file.Close()
err = json.NewEncoder(file).Encode(config)
if err != nil {
return err
}
return nil
}