本文整理汇总了Golang中github.com/hashicorp/consul/api.DefaultConfig函数的典型用法代码示例。如果您正苦于以下问题:Golang DefaultConfig函数的具体用法?Golang DefaultConfig怎么用?Golang DefaultConfig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DefaultConfig函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getClient
// get a client handle for a specified address (or the local agent if "")
func getClient(address string) (*api.Client, error) {
config := api.DefaultConfig()
if address != "" {
config.Address = address
}
return api.NewClient(config)
}
示例2: NewConsulBackend
func NewConsulBackend(address string) (Backend, error) {
if address == "" {
address = "http://127.0.0.1:8500/vault"
}
url, err := url.Parse(address)
if err != nil {
return nil, maskAny(err)
}
path := url.Path
// Ensure path is suffixed but not prefixed
if !strings.HasSuffix(path, "/") {
path += "/"
}
if strings.HasPrefix(path, "/") {
path = strings.TrimPrefix(path, "/")
}
consulConf := api.DefaultConfig()
consulConf.Address = url.Host
client, err := api.NewClient(consulConf)
if err != nil {
return nil, maskAny(err)
}
return &consulBackend{
path: path,
client: client,
kv: client.KV(),
}, nil
}
示例3: consulFactory
func consulFactory(conf map[string]string) (Client, error) {
path, ok := conf["path"]
if !ok {
return nil, fmt.Errorf("missing 'path' configuration")
}
config := consulapi.DefaultConfig()
if token, ok := conf["access_token"]; ok && token != "" {
config.Token = token
}
if addr, ok := conf["address"]; ok && addr != "" {
config.Address = addr
}
if scheme, ok := conf["scheme"]; ok && scheme != "" {
config.Scheme = scheme
}
client, err := consulapi.NewClient(config)
if err != nil {
return nil, err
}
return &ConsulClient{
Client: client,
Path: path,
}, nil
}
示例4: restore
/* File needs to be in the following format:
KEY1:VALUE1
KEY2:VALUE2
*/
func restore(ipaddress string, token string, infile string) {
config := api.DefaultConfig()
config.Address = ipaddress
config.Token = token
data, err := ioutil.ReadFile(infile)
if err != nil {
panic(err)
}
client, _ := api.NewClient(config)
kv := client.KV()
for _, element := range strings.Split(string(data), "\n") {
kvp := strings.Split(element, ":")
if len(kvp) > 1 {
decoded_value, decode_err := base64.StdEncoding.DecodeString(kvp[1])
if decode_err != nil {
panic(decode_err)
}
p := &api.KVPair{Key: kvp[0], Value: decoded_value}
_, err := kv.Put(p, nil)
if err != nil {
panic(err)
}
}
}
}
示例5: TestMatchTaskRun
func TestMatchTaskRun(t *testing.T) {
t.Log("here we are")
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
srv := NewTestServer(t)
defer srv.Stop()
conf := api.DefaultConfig()
conf.Address = srv.HTTPAddr
coord := NewConsulCoordinator(func(conf *ConsulConfig) {
conf.Address = srv.HTTPAddr
}).(*consulCoordinator)
coord.Start(&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0}, make(chan error))
receiver := NewMockInputManager(mockCtrl)
// NewMatchTask(coord, receiver, StreamID("match(cpu_util{service=monitoring}, user_perc{service=monitoring} by hostname, device in alarm(avg($1, 5min) )")
sid := StreamID("match(s1{t1=v1}, s2{t1=v1} by t2, t3 in alarm(avg(%s)<2 and avg(%s)>3))")
_, definition, err := ParseComputationID(sid)
assert.Nil(t, err)
taskInfo, _ := NewMatchTask(coord, receiver, sid, definition)
receiver.EXPECT().SubscribeTo(StreamID("alarm(avg(s1{t1=v1,t2=a,t3=1})<2 and avg(s2{t1=v1,t2=a,t3=1})>3)"), Timestamp(0), gomock.Any())
receiver.EXPECT().SubscribeTo(StreamID("alarm(avg(s1{t1=v1,t2=b,t3=1})<2 and avg(s2{t1=v1,t2=b,t3=1})>3)"), Timestamp(0), gomock.Any())
receiver.EXPECT().SubscribeTo(StreamID("alarm(avg(s1{t1=v1,t2=a,t3=2})<2 and avg(s2{t1=v1,t2=a,t3=2})>3)"), Timestamp(0), gomock.Any())
go taskInfo.Task.Run(make(chan error))
coord.RegisterAsPublisher(StreamID("s1{t1=v1,t2=a,t3=1,t4=x}"))
coord.RegisterAsPublisher(StreamID("s2{t1=v1,t2=a,t3=1,t4=x}"))
coord.RegisterAsPublisher(StreamID("s1{t1=v1,t2=b,t3=1,t4=y}"))
coord.RegisterAsPublisher(StreamID("s2{t1=v1,t2=a,t3=2,t4=x}"))
time.Sleep(2 * time.Second)
}
示例6: roleList
func roleList(c cli.Command) {
client, _ := api.NewClient(api.DefaultConfig())
agent := client.Agent()
services, err := agent.Services()
if err != nil {
log.Fatalln("err: ", err)
}
self, err := agent.Self()
if err != nil {
log.Fatalln("err: ", err)
}
for _, service := range services {
if service.Service == "cascade" {
fmt.Println(self["Config"]["NodeName"], self["Config"]["AdvertiseAddr"].(string)+":")
for _, role := range service.Tags {
fmt.Println(" -", role)
}
}
}
}
示例7: backup
func backup(ipaddress string, token string, outfile string) {
config := api.DefaultConfig()
config.Address = ipaddress
config.Token = token
client, _ := api.NewClient(config)
kv := client.KV()
pairs, _, err := kv.List("/", nil)
if err != nil {
panic(err)
}
sort.Sort(ByCreateIndex(pairs))
outstring := ""
for _, element := range pairs {
encoded_value := base64.StdEncoding.EncodeToString(element.Value)
outstring += fmt.Sprintf("%s:%s\n", element.Key, encoded_value)
}
file, err := os.Create(outfile)
if err != nil {
panic(err)
}
if _, err := file.Write([]byte(outstring)[:]); err != nil {
panic(err)
}
}
示例8: SetUpSuite
func (s *ConsulCatalogSuite) SetUpSuite(c *check.C) {
dockerHost := os.Getenv("DOCKER_HOST")
if dockerHost == "" {
// FIXME Handle windows -- see if dockerClient already handle that or not
dockerHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket)
}
// Make sure we can speak to docker
dockerClient, err := docker.NewClient(dockerHost)
c.Assert(err, checker.IsNil, check.Commentf("Error connecting to docker daemon"))
s.dockerClient = dockerClient
s.createComposeProject(c, "consul_catalog")
err = s.composeProject.Up()
c.Assert(err, checker.IsNil, check.Commentf("Error starting project"))
consul, err := s.GetContainer("integration-test-consul_catalog_consul_1")
c.Assert(err, checker.IsNil, check.Commentf("Error finding consul container"))
s.consulIP = consul.NetworkSettings.IPAddress
config := api.DefaultConfig()
config.Address = s.consulIP + ":8500"
consulClient, err := api.NewClient(config)
if err != nil {
c.Fatalf("Error creating consul client")
}
s.consulClient = consulClient
// Wait for consul to elect itself leader
time.Sleep(2000 * time.Millisecond)
}
示例9: verifyConsulUp
func verifyConsulUp(timeout string) error {
timeoutDur, err := time.ParseDuration(timeout)
if err != nil {
return err
}
if timeoutDur == 0 {
return nil
}
config := api.DefaultConfig()
config.Token = *consulToken
client, err := api.NewClient(config)
if err != nil {
return util.Errorf("Could not construct consul client: '%s'", err)
}
consulIsUp := make(chan struct{})
go func() {
for {
time.Sleep(200 * time.Millisecond)
err := Ping(client)
if err == nil {
consulIsUp <- struct{}{}
return
}
}
}()
select {
case <-time.After(timeoutDur):
return util.Errorf("Consul did not start or was not available after %v", timeoutDur)
case <-consulIsUp:
return nil
}
}
示例10: TestTaskWatcher
func TestTaskWatcher(t *testing.T) {
// Create a server
srv := NewTestServer(t)
defer srv.Stop()
conf := api.DefaultConfig()
conf.Address = srv.HTTPAddr
kv := NewSimpleKV(t, conf)
coord := NewConsulCoordinator(func(conf *ConsulConfig) {
conf.Address = srv.HTTPAddr
}).(*consulCoordinator)
newc, errc := coord.WatchTasks(nil)
add := []StreamID{
"task1",
"task2",
"task3",
}
remove := []StreamID{
"task1",
"task2",
}
expected := [][]StreamID{
{},
add[:1],
add[:2],
add[:3],
add[1:],
add[2:],
}
go func() {
for _, k := range add {
kv.Put(taskPrefix+string(k), nil)
}
for _, k := range remove {
kv.Delete(taskPrefix + string(k))
}
}()
var actual [][]StreamID
timeout := time.NewTimer(2 * time.Second)
for {
select {
case <-timeout.C:
t.Fatalf("Timeout!")
case k := <-newc:
t.Log("new set:", k)
ks := make([]StreamID, len(k), len(k))
for i := range k {
ks[i] = StreamID(k[i])
}
actual = append(actual, ks)
if len(actual) == len(expected) {
assert.Equal(t, expected, actual)
return
}
case err := <-errc:
t.Fatalf(err.Error())
}
}
}
示例11: restore
/* File needs to be in the following format:
KEY1:VALUE1
KEY2:VALUE2
*/
func restore(ipaddress string, token string, infile string) {
config := api.DefaultConfig()
config.Address = ipaddress
config.Token = token
file, err := os.Open(infile)
if err != nil {
panic(err)
}
data := make([]byte, 100)
_, err = file.Read(data)
if err != nil && err != io.EOF {
panic(err)
}
client, _ := api.NewClient(config)
kv := client.KV()
for _, element := range strings.Split(string(data), "\n") {
kvp := strings.Split(element, ":")
if len(kvp) > 1 {
p := &api.KVPair{Key: kvp[0], Value: []byte(kvp[1])}
_, err := kv.Put(p, nil)
if err != nil {
panic(err)
}
}
}
}
示例12: InitializeConsul
// InitializeConsul creates a new Consul client given
// a list of endpoints and optional tls config
func InitializeConsul(endpoints []string, options *store.Config) (store.Store, error) {
s := &Consul{}
// Create Consul client
config := api.DefaultConfig()
s.config = config
config.HttpClient = http.DefaultClient
config.Address = endpoints[0]
config.Scheme = "http"
// Set options
if options != nil {
if options.TLS != nil {
s.setTLS(options.TLS)
}
if options.ConnectionTimeout != 0 {
s.setTimeout(options.ConnectionTimeout)
}
if options.EphemeralTTL != 0 {
s.setEphemeralTTL(options.EphemeralTTL)
}
}
// Creates a new client
client, err := api.NewClient(config)
if err != nil {
log.Errorf("Couldn't initialize consul client..")
return nil, err
}
s.client = client
return s, nil
}
示例13: GetWriteMasterIP
/*
GetWriteMasterIP returns the write master IP for the service cluster.
*/
func (s *Service) GetWriteMasterIP() (ip string, err error) {
log.Trace(fmt.Sprintf(`services.Service<%s>#GetWriteMaster()`, s.Name))
client, err := consulapi.NewClient(consulapi.DefaultConfig())
if err != nil {
log.Error(fmt.Sprintf("services.Service<%s>#GetWriteMaster() ! %s", s.Name, err))
return
}
catalog := client.Catalog()
clusterID := os.Getenv("RDPGD_CLUSTER")
if clusterID == "" {
matrixName := os.Getenv(`RDPGD_MATRIX`)
matrixNameSplit := strings.SplitAfterN(matrixName, `-`, -1)
matrixColumn := os.Getenv(`RDPGD_MATRIX_COLUMN`)
for i := 0; i < len(matrixNameSplit)-1; i++ {
clusterID = clusterID + matrixNameSplit[i]
}
clusterID = clusterID + "c" + matrixColumn
}
svcs, _, err := catalog.Service(fmt.Sprintf(`%s-master`, clusterID), "", nil)
if err != nil {
log.Error(fmt.Sprintf(`services.Service<%s>#GetWriteMaster() ! %s`, s.Name, err))
return
}
if len(svcs) == 0 {
return "", nil
}
ip = svcs[0].Address
return
}
示例14: getServiceDirectory
func getServiceDirectory() ServiceDirectory {
// Lookup running services in Consul
directory := ServiceDirectory{}
client, _ := consulApi.NewClient(consulApi.DefaultConfig())
agent := client.Agent()
services, err := agent.Services()
if err != nil {
log.Println(err)
panic(err)
}
// Find all service proxies
for _, s := range services {
// We assume that if there is exactly one tag, then it's the tag for our dev env
if len(s.Tags) != 1 {
continue
}
envName := s.Tags[0]
log.Println("env:", envName)
log.Println("service:", s.Service)
log.Println("address:", s.Address)
log.Println("port:", s.Port)
log.Println()
directory[envName] = append(directory[envName], s)
}
return directory
}
示例15: New
// New creates a new Consul client given a list
// of endpoints and optional tls config
func New(endpoints []string, options *store.Config) (store.Store, error) {
if len(endpoints) > 1 {
return nil, ErrMultipleEndpointsUnsupported
}
s := &Consul{}
// Create Consul client
config := api.DefaultConfig()
s.config = config
config.HttpClient = http.DefaultClient
config.Address = endpoints[0]
config.Scheme = "http"
// Set options
if options != nil {
if options.TLS != nil {
s.setTLS(options.TLS)
}
if options.ConnectionTimeout != 0 {
s.setTimeout(options.ConnectionTimeout)
}
}
// Creates a new client
client, err := api.NewClient(config)
if err != nil {
return nil, err
}
s.client = client
return s, nil
}