consulagent.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package consulagent
  2. import (
  3. "fmt"
  4. log "github.com/sirupsen/logrus"
  5. "github.com/riomhaire/consul"
  6. )
  7. type ConsulServiceRegistry struct {
  8. name string
  9. applicationHost string
  10. applicationPort int
  11. consulHost string
  12. baseEndpoint string
  13. healthEndpoint string
  14. id string
  15. consulClient *consul.ConsulClient // This registers this service with consul - may extract this into a separate use case
  16. }
  17. func NewConsulServiceRegistry(consulHost, name, applicationHost string, applicationPort int, baseEndpoint, healthEndpoint string) *ConsulServiceRegistry {
  18. r := ConsulServiceRegistry{}
  19. r.baseEndpoint = baseEndpoint
  20. r.healthEndpoint = healthEndpoint
  21. r.name = name
  22. r.consulHost = consulHost
  23. r.applicationHost = applicationHost
  24. r.applicationPort = applicationPort
  25. return &r
  26. }
  27. func (a *ConsulServiceRegistry) Register() error {
  28. // Register with consol (if required)
  29. id := fmt.Sprintf("%v-%v-%v", a.name, a.applicationHost, a.applicationPort)
  30. a.id = id // This is our safe copy
  31. a.consulClient, _ = consul.NewConsulClient(a.consulHost)
  32. health := fmt.Sprintf("http://%v:%v%v", a.applicationHost, a.applicationPort, a.healthEndpoint)
  33. log.Printf("Registering with Consul at %v with %v %v\n", a.consulHost, a.baseEndpoint, health)
  34. a.consulClient.PeriodicRegister(id, a.name, a.applicationHost, a.applicationPort, a.baseEndpoint, health, 15)
  35. return nil
  36. }
  37. /*
  38. */
  39. func (a *ConsulServiceRegistry) Deregister() error {
  40. log.Printf("De Registering %v with Consul at %v with %v \n", a.id, a.consulHost, a.baseEndpoint)
  41. a.consulClient.DeRegister(a.id)
  42. return nil
  43. }