-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.go
88 lines (75 loc) · 1.67 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/gin-gonic/gin"
)
type Event struct {
ID int
Message string
}
func streamEvents(c *gin.Context) {
listener := make(chan interface{})
go sendEvents(listener)
c.Stream(func(w io.Writer) bool {
event := <-listener
if event != nil {
c.SSEvent("message", event)
return true
}
return false
})
}
func main() {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
fmt.Printf("Started...\n")
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.File("index.html")
})
r.GET("/stream", streamEvents)
r.GET("/status", func(c *gin.Context) {
containers, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})
if err != nil {
panic(err)
}
u, err := json.Marshal(containers)
if err != nil {
panic(err)
}
c.DataFromReader(http.StatusOK,
int64(len(string(u))), gin.MIMEJSON, strings.NewReader(string(u)), nil)
})
r.Run() // listen and serve on 0.0.0.0:8080
}
func sendEvents(listener chan interface{}) {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
msgs, errs := cli.Events(ctx, types.EventsOptions{})
var i int
for {
i ++
select {
case err := <-errs:
fmt.Println(err)
listener <- Event{i, "update"}
case msg := <-msgs:
fmt.Println(msg)
listener <- Event{i, "update"}
}
}
}