-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
101 lines (91 loc) · 2.63 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"fmt"
"os"
)
// Google Cloud Storage Buckets (uncomment below to enable)
// StorageBucketName = "<your-storage-bucket>"
// StorageBucket, err = configureStorage(StorageBucketName)
type PostgresConfig struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
Name string `json:"name"`
}
func (c PostgresConfig) Dialect() string {
return "postgres"
}
func (c PostgresConfig) ConnectionInfo() string {
// We are going to provide two potential connection
// info strings based on whether a password is present.
if c.Password == "" {
return fmt.Sprintf("host=%s port=%d user=%s dbname=%s "+
"sslmode=disable", c.Host, c.Port, c.User, c.Name)
}
return fmt.Sprintf("host=%s port=%d user=%s password=%s "+
"dbname=%s sslmode=disable", c.Host, c.Port, c.User,
c.Password, c.Name)
}
func DefaultPostgresConfig() PostgresConfig {
return PostgresConfig{
Host: "localhost",
Port: 5432,
User: "postgres",
Password: "Mutoworld2013!",
Name: "muto_dev",
}
}
type Config struct {
Port int `json:"port"`
Env string `json:"env"`
Pepper string `json:"pepper"`
HMACKey string `json:"hmac_key"`
Database PostgresConfig `json:"database"`
}
func (c Config) IsProd() bool {
return c.Env == "prod"
}
func DefaultConfig() Config {
return Config{
Port: 8080,
Env: "dev",
Pepper: "secret-random-string",
HMACKey: "secret-hmac-key",
Database: DefaultPostgresConfig(),
}
}
func LoadConfig(configReq bool) Config {
// Open the config file
f, err := os.Open(".config")
if err != nil {
if configReq {
panic(err)
}
// If there was an error opening the file,
// print out a message saying we are
// using the default config and return it.
fmt.Println("Using the default config...")
return DefaultConfig()
}
// If we opened the config file successfully we
// are going to create a Config variable to load it into.
var c Config
// We also need a JSON decoder, which will
// read from the file we opened when decoding.
dec := json.NewDecoder(f)
// We then decode the file and place the results in c,
// the Config variable we created for the results. The decoder
// knows how to decode the data because of the struct tags
// (eg `json:"port"`) we added to our Config and PostgresConfig
// fields, much like GORM uses struct tags to know
// which database column each field maps to.
err = dec.Decode(&c)
if err != nil {
panic(err)
}
// If all goes well, return the loaded config.
fmt.Println("Successfully loaded .config")
return c
}