Skip to content

Instantly share code, notes, and snippets.

@Abdulsametileri
Created May 22, 2022 19:27
Show Gist options
  • Save Abdulsametileri/9cc32f30ddb6523cd77125af8388d7bb to your computer and use it in GitHub Desktop.
Save Abdulsametileri/9cc32f30ddb6523cd77125af8388d7bb to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"time"
)
type Registrar struct {
Interval time.Duration
DockerCLI *client.Client
SRegistry *ServiceRegistry
}
const (
HelloServiceImageName = "hello"
ContainerRunningState = "running"
)
func (r *Registrar) Observe() {
for range time.Tick(r.Interval) {
cList, _ := r.DockerCLI.ContainerList(context.Background(), types.ContainerListOptions{
All: true,
})
if len(cList) == 0 {
r.SRegistry.RemoveAll()
continue
}
for _, c := range cList {
if c.Image != HelloServiceImageName {
continue
}
_, exist := r.SRegistry.GetByContainerID(c.ID)
if c.State == ContainerRunningState {
if !exist {
addr := fmt.Sprintf("http://localhost:%d", c.Ports[0].PublicPort)
r.SRegistry.Add(c.ID, addr)
}
} else {
if exist {
r.SRegistry.RemoveByContainerID(c.ID)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment