-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
97 lines (82 loc) · 2.3 KB
/
main.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
89
90
91
92
93
94
95
96
97
package main
import (
"context"
"encoding/json"
"net/http"
"strings"
"time"
"golang.org/x/exp/slices"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/gin-gonic/gin"
)
type responseContainer struct {
ID string `json:"id"`
PrimaryName string `json:"name"`
Names []string `json:"names"`
State string `json:"state"`
Status string `json:"status"`
Image string `json:"image"`
ImageHash string `json:"image_hash"`
}
type response struct {
Containers []responseContainer `json:"containers"`
Time int64 `json:"time"`
}
func main() {
router := gin.Default()
router.GET("/", listContainers)
router.GET("/:names", listContainers)
router.Run()
}
func getContainers() ([]responseContainer, error) {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return nil, err
}
containers, err := cli.ContainerList(ctx, container.ListOptions{All: true})
if err != nil {
return nil, err
}
output := make([]responseContainer, len(containers))
for i, container := range containers {
output[i] = responseContainer{
ID: container.ID,
State: container.State,
Status: container.Status,
Image: container.Image,
ImageHash: container.ImageID[7:],
}
for _, name := range container.Names {
output[i].Names = append(output[i].Names, strings.TrimPrefix(name, "/"))
}
output[i].PrimaryName = output[i].Names[0]
}
return output, nil
}
func listContainers(c *gin.Context) {
containers, err := getContainers()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if c.Param("names") != "" {
names := strings.Split(c.Param("names"), ",")
filteredContainers := make([]responseContainer, 0)
for _, container := range containers {
for _, name := range names {
if slices.Contains(container.Names, name) {
filteredContainers = append(filteredContainers, container)
}
}
}
containers = filteredContainers
}
responseJson, err := json.Marshal(response{containers, time.Now().UnixMilli()})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Data(http.StatusOK, gin.MIMEJSON, responseJson)
}