package consul import ( "fmt" "net/http" "strconv" "time" consul "github.com/hashicorp/consul/api" ) type Service struct { Name string Address string appID string domain string port int ttl time.Duration agent *consul.Agent kv *consul.KV } var ErrServiceUnavailable = fmt.Errorf("Service is unavailable") func NewService(servAddr, id, name, hostname, domain string, appPort int) (*Service, error) { s := new(Service) s.Name = name s.Address = hostname s.appID = id s.domain = domain s.port = appPort s.ttl = time.Second * 15 client, err := consul.NewClient(newClientConfig(servAddr)) if err != nil { return nil, err } s.agent = client.Agent() s.kv = client.KV() return s, nil } func newClientConfig(serverAddr string) *consul.Config { conf := consul.DefaultConfig() conf.Address = serverAddr return conf } func (s *Service) GetID() string { return fmt.Sprintf("%s_%s", s.Name, s.appID) } func (s *Service) GetFullAddr() string { return fmt.Sprintf("http://%s:%d/", s.Address, s.port) } func (s *Service) Register() error { def := &consul.AgentServiceRegistration{ ID: s.GetID(), Name: s.Name, Address: s.Address, Port: s.port, Tags: s.getTags(), Check: &consul.AgentServiceCheck{ TTL: s.ttl.String(), DeregisterCriticalServiceAfter: "5s", }, } if err := s.agent.ServiceRegister(def); err != nil { return err } go func(s *Service) { // startup register ticker := time.NewTicker(time.Millisecond * 100) for range ticker.C { ok, _ := s.healthCheck() if ok { ticker.Stop() } } }(s) go func(s *Service) { // TTL interval := s.ttl - time.Second*2 ticker := time.NewTicker(interval) for range ticker.C { _, err := s.healthCheck() if err != nil { fmt.Printf("TTL Error: %v\n", err) } } }(s) return nil } func (s *Service) Unregister() error { return s.agent.ServiceDeregister(s.GetID()) } func (s *Service) KV() *consul.KV { return s.kv } func (s *Service) healthCheck() (bool, error) { alive := func() bool { client := &http.Client{} healthUrl := s.GetFullAddr() + "health" req, err := http.NewRequest(http.MethodGet, healthUrl, nil) if err != nil { return false } req.Header.Set("User-Agent", "Health Check") resp, err := client.Do(req) if err != nil { return false } defer resp.Body.Close() return resp.StatusCode == http.StatusOK }() if alive { if err := s.agent.PassTTL("service:"+s.GetID(), "OK"); err != nil { return false, err } return true, nil } if err := s.agent.FailTTL("service:"+s.GetID(), ErrServiceUnavailable.Error()); err != nil { return false, err } return false, ErrServiceUnavailable } func (s *Service) getTags() []string { tags := []string{ "traefik.enable=true", "traefik.http.routers." + s.Name + ".rule=Header(`X-API-SERVICE`, `" + s.Name + "`)", "traefik.http.routers." + s.Name + ".entryPoints=https", "traefik.http.routers." + s.Name + ".tls=true", "traefik.http.routers." + s.Name + ".service=" + s.Name, "traefik.http.routers." + s.Name + ".middlewares=compress,requestid", "traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http", "traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.port), "traefik.http.middlewares.compress.compress=true", "traefik.http.middlewares.requestid.plugin.requestid.headerName=X-Request-ID", "traefik.tls.certificates.certfile=/certs/client.cert", "traefik.tls.certificates.keyfile=/certs/client.key", // "traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false", // "traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + "=" + bFullAddr, // "traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + ".url=" + bFullAddr, // "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.path=/health", // "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.interval=10s", } return tags }