github.com/jxgolibs/go-oauth2-server@v1.0.1/config/consul.go (about) 1 package config 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/http" 7 "os" 8 9 "github.com/RichardKnop/go-oauth2-server/log" 10 "github.com/hashicorp/consul/api" 11 ) 12 13 var ( 14 consulEndpoint = "http://localhost:8500" 15 consulCertFile, consulKeyFile, consulCaFile string 16 consulConfigPath = "/config/go_oauth2_server.json" 17 ) 18 19 type consulBackend struct{} 20 21 func (b *consulBackend) InitConfigBackend() { 22 // Overwrite default values with environment variables if they are set 23 if os.Getenv("CONSUL_ENDPOINT") != "" { 24 consulEndpoint = os.Getenv("CONSUL_ENDPOINT") 25 } 26 if os.Getenv("CONSUL_CERT_FILE") != "" { 27 consulCertFile = os.Getenv("CONSUL_CERT_FILE") 28 } 29 if os.Getenv("CONSUL_KEY_FILE") != "" { 30 consulKeyFile = os.Getenv("CONSUL_KEY_FILE") 31 } 32 if os.Getenv("CONSUL_CA_FILE") != "" { 33 consulCaFile = os.Getenv("CONSUL_CA_FILE") 34 } 35 if os.Getenv("CONSUL_CONFIG_PATH") != "" { 36 consulConfigPath = os.Getenv("CONSUL_CONFIG_PATH") 37 } 38 } 39 40 //LoadConfig gets the JSON from Consul and unmarshals it to the config object 41 func (b *consulBackend) LoadConfig() (*Config, error) { 42 43 cli, err := newConsulClient(consulEndpoint, consulCertFile, consulKeyFile, consulCaFile) 44 if err != nil { 45 return nil, err 46 } 47 48 // Read from remote config the first time 49 50 resp, _, err := cli.KV().Get(consulConfigPath, nil) 51 52 if err != nil { 53 return nil, err 54 } 55 56 if resp == nil { 57 return nil, fmt.Errorf("key not found: %s", consulConfigPath) 58 } 59 60 // Unmarshal the config JSON into the cnf object 61 newCnf := new(Config) 62 63 if err := json.Unmarshal(resp.Value, newCnf); err != nil { 64 return nil, err 65 } 66 67 return newCnf, nil 68 } 69 70 // RefreshConfig sets config through the pointer so config actually gets refreshed 71 func (b *consulBackend) RefreshConfig(newCnf *Config) { 72 *Cnf = *newCnf 73 } 74 75 func newConsulClient(theEndpoint, certFile, keyFile, caFile string) (*api.Client, error) { 76 // Log the consul endpoint for debugging purposes 77 log.INFO.Printf("CONSUL Endpoint: %s", theEndpoint) 78 79 consulConfig := api.DefaultConfig() 80 81 consulConfig.Address = theEndpoint 82 83 // Optionally, configure TLS transport 84 if certFile != "" && keyFile != "" && caFile != "" { 85 86 tlsConfig, err := api.SetupTLSConfig(&api.TLSConfig{ 87 CertFile: certFile, 88 KeyFile: keyFile, 89 CAFile: caFile, 90 InsecureSkipVerify: true, 91 }) 92 93 if err != nil { 94 return nil, err 95 } 96 97 consulConfig.HttpClient.Transport = &http.Transport{ 98 TLSClientConfig: tlsConfig, 99 } 100 101 } 102 103 return api.NewClient(consulConfig) 104 105 }