import "github.com/hashicorp/consul/api" // Create a new Consul API client client, err := api.NewClient(api.DefaultConfig()) if err != nil { panic(err) }
// Get the value of a key from Consul kv := client.KV() pair, _, err := kv.Get("my/key", nil) if err != nil { panic(err) } if pair != nil { value := string(pair.Value) fmt.Printf("Key: %s Value: %s\n", pair.Key, value) }
import "github.com/hashicorp/consul/api" // Create a new Consul API client client, err := api.NewClient(api.DefaultConfig()) if err != nil { panic(err) }
// Create a new ServiceEntry object entry := &api.ServiceEntry{ Node: &api.Node{ ID: "my-service-1", Name: "my-service", Meta: map[string]string{ "version": "1.0.0", }, }, Service: &api.AgentService{ ID: "my-service-1", Name: "my-service", Tags: []string{"tag1", "tag2"}, Port: 8080, Check: &api.AgentServiceCheck{ HTTP: "http://localhost:8080/health", Interval: "10s", }, }, }
// Register the service with Consul registration := &api.AgentServiceRegistration{ Name: "my-service", ID: "my-service-1", Tags: []string{"tag1", "tag2"}, Port: 8080, Check: &api.AgentServiceCheck{ HTTP: "http://localhost:8080/health", Interval: "10s", }, } err = client.Agent().ServiceRegister(registration) if err != nil { panic(err) }In both examples, we used the `github.com/hashicorp/consul/api` package library to interact with the Consul API. This package library provides a consistent and easy-to-use interface for working with Consul from a Go application.