Step 4: Can create containers

This commit is contained in:
nemunaire 2024-05-29 16:00:19 +02:00
parent fe9b062c36
commit ec71ff464f
3 changed files with 20 additions and 3 deletions

View File

@ -1,13 +1,14 @@
package main
import (
"bytes"
"fmt"
"io"
"net"
"net/http"
)
func curl(socket, method, path string) (io.ReadCloser, error) {
func curl(socket, method, path string, body []byte) (io.ReadCloser, error) {
socketDial := func(proto, addr string) (conn net.Conn, err error) {
return net.Dial("unix", socket)
}
@ -19,11 +20,13 @@ func curl(socket, method, path string) (io.ReadCloser, error) {
Transport: tr,
}
req, err := http.NewRequest(method, path, nil)
req, err := http.NewRequest(method, path, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("Error creating request: %w\n", err)
}
req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error performing request: %w\n", err)

View File

@ -21,7 +21,12 @@
<tbody id="containers">
</tbody>
</table>
<div style="text-align: center">
<button type="button" id="create-btn">Create container</button>
</div>
<script>
document.getElementById('create-btn').addEventListener("click", () => fetch('/containers', {method: 'POST'}));
fetch('/containers').then(
(res) => res.json()
).then(

11
main.go
View File

@ -12,7 +12,16 @@ var staticfiles embed.FS
func main() {
http.HandleFunc("GET /containers", func(w http.ResponseWriter, r *http.Request) {
rd, err := curl("/var/run/docker.sock", "GET", "http://d/v1.43/containers/json?all=true")
rd, err := curl("/var/run/docker.sock", "GET", "http://d/v1.43/containers/json?all=true", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
io.Copy(w, rd)
}
})
http.HandleFunc("POST /containers", func(w http.ResponseWriter, r *http.Request) {
rd, err := curl("/var/run/docker.sock", "POST", "http://d/v1.43/containers/create", []byte(`{"Image": "alpine:latest", "Cmd": ["echo", "Hello Go Meetup!"]}`))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {