github.com/jxgolibs/go-oauth2-server@v1.0.1/config/factory.go (about) 1 package config 2 3 import ( 4 "os" 5 "time" 6 7 "github.com/RichardKnop/go-oauth2-server/log" 8 ) 9 10 var ( 11 configLoaded bool 12 dialTimeout = 5 * time.Second 13 contextTimeout = 5 * time.Second 14 reloadDelay = time.Second * 10 15 ) 16 17 // Cnf ... 18 // Let's start with some sensible defaults 19 var Cnf = &Config{ 20 Database: DatabaseConfig{ 21 Type: "postgres", 22 Host: "postgres", 23 Port: 5432, 24 User: "go_oauth2_server", 25 Password: "", 26 DatabaseName: "go_oauth2_server", 27 MaxIdleConns: 5, 28 MaxOpenConns: 5, 29 }, 30 Oauth: OauthConfig{ 31 AccessTokenLifetime: 3600, // 1 hour 32 RefreshTokenLifetime: 1209600, // 14 days 33 AuthCodeLifetime: 3600, // 1 hour 34 }, 35 Session: SessionConfig{ 36 Secret: "test_secret", 37 Path: "/", 38 MaxAge: 86400 * 7, // 7 days 39 HTTPOnly: true, 40 }, 41 IsDevelopment: true, 42 } 43 44 // NewConfig loads configuration from etcd and returns *Config struct 45 // It also starts a goroutine in the background to keep config up-to-date 46 func NewConfig(mustLoadOnce bool, keepReloading bool, backendType string) *Config { 47 if configLoaded { 48 return Cnf 49 } 50 51 var backend Backend 52 53 switch backendType { 54 case "etcd": 55 backend = new(etcdBackend) 56 case "consul": 57 backend = new(consulBackend) 58 default: 59 log.FATAL.Printf("%s is not a valid backend", backendType) 60 os.Exit(1) 61 } 62 63 backend.InitConfigBackend() 64 65 // If the config must be loaded once successfully 66 if mustLoadOnce && !configLoaded { 67 // Read from remote config the first time 68 newCnf, err := backend.LoadConfig() 69 70 if err != nil { 71 log.FATAL.Print(err) 72 os.Exit(1) 73 } 74 75 // Refresh the config 76 backend.RefreshConfig(newCnf) 77 78 // Set configLoaded to true 79 configLoaded = true 80 log.INFO.Print("Successfully loaded config for the first time") 81 } 82 83 if keepReloading { 84 // Open a goroutine to watch remote changes forever 85 go func() { 86 for { 87 // Delay after each request 88 <-time.After(reloadDelay) 89 90 // Attempt to reload the config 91 newCnf, err := backend.LoadConfig() 92 if err != nil { 93 log.ERROR.Print(err) 94 continue 95 } 96 97 // Refresh the config 98 backend.RefreshConfig(newCnf) 99 100 // Set configLoaded to true 101 configLoaded = true 102 log.INFO.Print("Successfully reloaded config") 103 } 104 }() 105 } 106 107 return Cnf 108 }