Created
May 22, 2022 19:27
-
-
Save Abdulsametileri/9cc32f30ddb6523cd77125af8388d7bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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