2014-07-25 23:03:17 +02:00
|
|
|
package consul
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
2016-08-12 04:22:41 +02:00
|
|
|
"net/http"
|
2017-03-20 14:00:44 +01:00
|
|
|
"strings"
|
2014-07-25 23:03:17 +02:00
|
|
|
|
2015-01-07 02:11:29 +01:00
|
|
|
consulapi "github.com/hashicorp/consul/api"
|
2014-07-25 23:03:17 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
Datacenter string `mapstructure:"datacenter"`
|
|
|
|
Address string `mapstructure:"address"`
|
2015-05-07 01:12:32 +02:00
|
|
|
Scheme string `mapstructure:"scheme"`
|
2017-03-20 14:00:44 +01:00
|
|
|
HttpAuth string `mapstructure:"http_auth"`
|
2016-08-12 04:22:41 +02:00
|
|
|
Token string `mapstructure:"token"`
|
|
|
|
CAFile string `mapstructure:"ca_file"`
|
|
|
|
CertFile string `mapstructure:"cert_file"`
|
|
|
|
KeyFile string `mapstructure:"key_file"`
|
2014-07-25 23:03:17 +02:00
|
|
|
}
|
|
|
|
|
2015-01-22 21:45:55 +01:00
|
|
|
// Client() returns a new client for accessing consul.
|
2014-07-25 23:03:17 +02:00
|
|
|
//
|
|
|
|
func (c *Config) Client() (*consulapi.Client, error) {
|
|
|
|
config := consulapi.DefaultConfig()
|
|
|
|
if c.Datacenter != "" {
|
|
|
|
config.Datacenter = c.Datacenter
|
|
|
|
}
|
|
|
|
if c.Address != "" {
|
|
|
|
config.Address = c.Address
|
|
|
|
}
|
2015-05-07 01:12:32 +02:00
|
|
|
if c.Scheme != "" {
|
|
|
|
config.Scheme = c.Scheme
|
|
|
|
}
|
2016-08-12 04:22:41 +02:00
|
|
|
|
|
|
|
tlsConfig := &consulapi.TLSConfig{}
|
|
|
|
tlsConfig.CAFile = c.CAFile
|
|
|
|
tlsConfig.CertFile = c.CertFile
|
|
|
|
tlsConfig.KeyFile = c.KeyFile
|
|
|
|
cc, err := consulapi.SetupTLSConfig(tlsConfig)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
config.HttpClient.Transport.(*http.Transport).TLSClientConfig = cc
|
|
|
|
|
2017-03-20 14:00:44 +01:00
|
|
|
if c.HttpAuth != "" {
|
|
|
|
var username, password string
|
|
|
|
if strings.Contains(c.HttpAuth, ":") {
|
|
|
|
split := strings.SplitN(c.HttpAuth, ":", 2)
|
|
|
|
username = split[0]
|
|
|
|
password = split[1]
|
|
|
|
} else {
|
|
|
|
username = c.HttpAuth
|
|
|
|
}
|
2017-03-28 17:06:39 +02:00
|
|
|
config.HttpAuth = &consulapi.HttpBasicAuth{Username: username, Password: password}
|
2017-03-20 14:00:44 +01:00
|
|
|
}
|
|
|
|
|
2015-09-23 09:43:48 +02:00
|
|
|
if c.Token != "" {
|
2015-10-15 10:06:52 +02:00
|
|
|
config.Token = c.Token
|
2015-09-23 09:43:48 +02:00
|
|
|
}
|
2016-08-12 04:22:41 +02:00
|
|
|
|
2014-07-25 23:03:17 +02:00
|
|
|
client, err := consulapi.NewClient(config)
|
|
|
|
|
2015-05-07 01:12:32 +02:00
|
|
|
log.Printf("[INFO] Consul Client configured with address: '%s', scheme: '%s', datacenter: '%s'",
|
|
|
|
config.Address, config.Scheme, config.Datacenter)
|
2014-07-25 23:03:17 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return client, nil
|
|
|
|
}
|