package consul import ( "fmt" "log" "net/http" "strconv" "time" consul "github.com/hashicorp/consul/api" ) type Service struct { Name string Address string Port int TTL time.Duration ConsulAgent *consul.Agent } var ErrServiceUnavailable = fmt.Errorf("Service is unavailable") func NewService(serverAddr, appName, appDomain string, appPort int) (*Service, error) { s := new(Service) s.Name = appName s.Address = appDomain s.Port = appPort s.TTL = time.Second * 15 client, err := consul.NewClient(newClientConfig(serverAddr)) if err != nil { return nil, err } s.ConsulAgent = client.Agent() return s, nil } func newClientConfig(serverAddr string) *consul.Config { conf := consul.DefaultConfig() conf.Address = serverAddr return conf } func (s *Service) Register() error { def := &consul.AgentServiceRegistration{ // ID: s.Name, Name: s.Name, Address: s.Address, Port: s.Port, Tags: s.getTags(), Check: &consul.AgentServiceCheck{ TTL: s.TTL.String(), }, } if err := s.ConsulAgent.ServiceRegister(def); err != nil { return err } go s.UpdateTTL(def) return nil } func (s *Service) Unregister() error { return s.ConsulAgent.ServiceDeregister(s.Name) } func (s *Service) UpdateTTL(service *consul.AgentServiceRegistration) { ticker := time.NewTicker(s.TTL / 2) for range ticker.C { ok, err := s.check() if !ok { if err := s.ConsulAgent.FailTTL("service:"+s.Name, err.Error()); err != nil { log.Println(err) } } else { if err := s.ConsulAgent.PassTTL("service:"+s.Name, "OK"); err != nil { log.Println(err) } } } } func (s *Service) check() (bool, error) { client := &http.Client{} healthUrl := fmt.Sprintf("http://%s:%d/health", s.Address, s.Port) req, err := http.NewRequest(http.MethodGet, healthUrl, nil) if err != nil { return false, ErrServiceUnavailable } req.Header.Set("User-Agent", "Health Check") resp, err := client.Do(req) if err != nil { return false, ErrServiceUnavailable } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { return true, nil } return false, ErrServiceUnavailable } func (s *Service) getTags() []string { name, addr, port := s.Name, s.Address, strconv.Itoa(s.Port) tags := []string{ "traefik.enable=true", "traefik.http.routers." + name + ".rule=Host(`" + addr + "`)", "traefik.http.routers." + name + ".entryPoints=https", "traefik.http.routers." + name + ".service=" + name, "traefik.http.routers." + name + ".middlewares=compress,requestid", "traefik.http.routers." + name + ".tls=true", "traefik.http.services." + name + ".loadbalancer.server.scheme=http", "traefik.http.services." + name + ".loadbalancer.server.port=" + port, "traefik.http.services." + name + ".loadbalancer.passhostheader=false", "traefik.http.middlewares.compress.compress=true", "traefik.http.middlewares.requestid.plugin.requestid.headerName=X-Request-ID", // "traefik.http.services." + name + ".loadbalancer.healthcheck.path=/health", // "traefik.http.services." + name + ".loadbalancer.healthcheck.interval=10s", // "traefik.tls.certificates.certfile=/certs/client.cert", // "traefik.tls.certificates.keyfile=/certs/client.key", } return tags }