forked from keyz182/go-oauth2-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
factory.go
108 lines (91 loc) · 2.21 KB
/
factory.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
102
103
104
105
106
107
108
package config
import (
"os"
"time"
"github.com/RichardKnop/go-oauth2-server/log"
)
var (
configLoaded bool
dialTimeout = 5 * time.Second
contextTimeout = 5 * time.Second
reloadDelay = time.Second * 10
)
// Cnf ...
// Let's start with some sensible defaults
var Cnf = &Config{
Database: DatabaseConfig{
Type: "postgres",
Host: "postgres",
Port: 5432,
User: "go_oauth2_server",
Password: "",
DatabaseName: "go_oauth2_server",
MaxIdleConns: 5,
MaxOpenConns: 5,
},
Oauth: OauthConfig{
AccessTokenLifetime: 3600, // 1 hour
RefreshTokenLifetime: 1209600, // 14 days
AuthCodeLifetime: 3600, // 1 hour
},
Session: SessionConfig{
Secret: "test_secret",
Path: "/",
MaxAge: 86400 * 7, // 7 days
HTTPOnly: true,
},
IsDevelopment: true,
}
// NewConfig loads configuration from etcd and returns *Config struct
// It also starts a goroutine in the background to keep config up-to-date
func NewConfig(mustLoadOnce bool, keepReloading bool, backendType string) *Config {
if configLoaded {
return Cnf
}
var backend Backend
switch backendType {
case "etcd":
backend = new(etcdBackend)
case "consul":
backend = new(consulBackend)
default:
log.FATAL.Printf("%s is not a valid backend", backendType)
os.Exit(1)
}
backend.InitConfigBackend()
// If the config must be loaded once successfully
if mustLoadOnce && !configLoaded {
// Read from remote config the first time
newCnf, err := backend.LoadConfig()
if err != nil {
log.FATAL.Print(err)
os.Exit(1)
}
// Refresh the config
backend.RefreshConfig(newCnf)
// Set configLoaded to true
configLoaded = true
log.INFO.Print("Successfully loaded config for the first time")
}
if keepReloading {
// Open a goroutine to watch remote changes forever
go func() {
for {
// Delay after each request
<-time.After(reloadDelay)
// Attempt to reload the config
newCnf, err := backend.LoadConfig()
if err != nil {
log.ERROR.Print(err)
continue
}
// Refresh the config
backend.RefreshConfig(newCnf)
// Set configLoaded to true
configLoaded = true
log.INFO.Print("Successfully reloaded config")
}
}()
}
return Cnf
}