Skip to content

Instantly share code, notes, and snippets.

@brianshumate
Created April 24, 2017 20:35
Show Gist options
  • Save brianshumate/24a8c65c3af580bd11814028bb2ff383 to your computer and use it in GitHub Desktop.
Save brianshumate/24a8c65c3af580bd11814028bb2ff383 to your computer and use it in GitHub Desktop.
Consul Roll — A Rick Roll service registrator for Consul
package main
import (
"log"
"os"
"strconv"
"time"
"github.com/hashicorp/consul/api"
)
// RegisterService registers a service into the catalog
func RegisterService(ag *api.Agent, service, hostname, node, protocol string, port int) error {
consulService := api.AgentServiceRegistration{
ID: service,
Name: service,
Tags: []string{time.Now().Format("Jan 02 15:04:05.000 EST")},
Port: port,
Check: &api.AgentServiceCheck{
Script: "curl --connect-timeout=5 " + protocol + "://" + hostname + ":" + strconv.Itoa(port),
Interval: "10s",
Timeout: "8s",
TTL: "",
HTTP: protocol + "://" + hostname + ":" + strconv.Itoa(port),
Status: "passing",
},
Checks: api.AgentServiceChecks{},
}
err := ag.ServiceRegister(&consulService)
if err != nil {
return err
}
return err
}
func getenv(key, fallback string) string {
value := os.Getenv(key)
if len(value) == 0 {
log.Printf("✳️ Ricky needs a node! Set CONSUL_HTTP_ADDR to host:port")
log.Printf("✳️ Address set to: localhost:8500 (which might not work!)")
return fallback
}
return value
}
func main() {
consulAddress := getenv("CONSUL_HTTP_ADDR", "localhost:8500")
config := api.DefaultConfig()
config.Address = consulAddress
config.Datacenter = "dc1"
client, err := api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatalf("🚫 Dave, I cannot do the thing with the client: %v\n", err)
return
}
srvRegistrator := client.Agent()
log.Printf("🎤 Rickrolling the Consul cluster node at %v ...",
consulAddress)
if err = RegisterService(srvRegistrator,
"Never gonna give you up",
"www.youtube.com/watch?v=dQw4w9WgXcQ",
"youtube",
"https",
443); err != nil {
log.Fatalf("🚫 Dave, I cannot do the thing with the service: %v", err)
return
}
if err = RegisterService(srvRegistrator,
"Never gonna let you down",
"www.youtube.com/watch?v=dQw4w9WgXcQ",
"rickroll",
"https",
443); err != nil {
log.Fatalf("🚫 Dave, I cannot do the thing with the service: %v", err)
return
}
if err = RegisterService(srvRegistrator,
"Never gonna run around and desert you",
"www.youtube.com/watch?v=dQw4w9WgXcQ",
"youtube",
"https",
443); err != nil {
log.Fatalf("Service registration failed: %v", err)
return
}
log.Printf("✨ Success, cluster 9001%% more awesome!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment