-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
128 lines (99 loc) · 2.33 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"fmt"
"github.com/fsouza/go-dockerclient"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/rainbowism/gin-pongo2"
"net"
"net/http"
"os"
)
var wsupgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func vncStreamHandler(c *gin.Context) {
conn, err := wsupgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
fmt.Println("Failed to set websocket upgrade: %+v", err)
return
}
address := fmt.Sprintf("%s:5901", c.Param("ip"))
fmt.Println("proxying ", address)
// proxy
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
fmt.Println("cannot resolve address")
return
}
tcpConn, err := net.DialTCP("tcp", nil, addr)
if err != nil {
fmt.Println("cannot connect to address")
return
}
defer tcpConn.Close()
go func() {
for {
data := make([]byte, 100)
n, err := tcpConn.Read(data)
if err != nil {
fmt.Println("error while reading data from tcp", err)
return
}
conn.WriteMessage(websocket.BinaryMessage, data[0:n])
}
}()
for {
t, msg, err := conn.ReadMessage()
if t != websocket.BinaryMessage {
fmt.Println("received wrong websocket message type")
return
}
if err != nil {
fmt.Println("error while reading data from WS", err)
return
}
tcpConn.Write(msg)
}
}
func main() {
endpoint := "unix:///var/run/docker.sock"
client, _ := docker.NewClient(endpoint)
switch os.Getenv("MODE") {
case "RELEASE":
gin.SetMode(gin.ReleaseMode)
default:
gin.SetMode(gin.DebugMode)
}
r := gin.New()
r.Use(gin.Recovery())
if gin.IsDebugging() {
r.HTMLRender = render.NewDebug("templates")
} else {
r.HTMLRender = render.NewProduction("templates")
}
r.Static("/static", "./static")
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/new", func(c *gin.Context) {
container, err := client.CreateContainer(docker.CreateContainerOptions{
Config: &docker.Config{
Image: "caas",
},
})
fmt.Println(err)
err = client.StartContainer(container.ID, nil)
fmt.Println(err, container)
container, err = client.InspectContainer(container.ID)
ip := container.NetworkSettings.IPAddress
c.HTML(http.StatusOK, "new.html", render.Context{
"ip": ip,
})
})
r.GET("/ws/:ip", vncStreamHandler)
r.Run() // listen and server on 0.0.0.0:8080
}