Some experimenting with docker api

main
Jef Roosens 2022-02-19 22:25:52 +01:00
parent 57c4af0aaf
commit e6a1d32f0e
Signed by untrusted user: Jef Roosens
GPG Key ID: B580B976584B5F30
4 changed files with 43 additions and 7 deletions

View File

@ -7,4 +7,5 @@ end_of_line = lf
insert_final_newline = true insert_final_newline = true
[*.v] [*.v]
indent_style = space # vfmt wants it :(
indent_style = tab

View File

@ -3,5 +3,5 @@ module main
import docker import docker
fn build() { fn build() {
println(docker.containers() or { panic('yeet') }) println(docker.pull('archlinux', 'latest') or { panic('yeetus') })
} }

View File

@ -4,8 +4,8 @@ import json
import net.urllib import net.urllib
struct Container { struct Container {
id string id string [json: Id]
names []string names []string [json: Names]
} }
pub fn containers() ?[]Container { pub fn containers() ?[]Container {

View File

@ -3,20 +3,20 @@ module docker
import net.unix import net.unix
import net.urllib import net.urllib
import net.http import net.http
import json
const socket = '/var/run/docker.sock' const socket = '/var/run/docker.sock'
const buf_len = 1024 const buf_len = 1024
fn request(method string, url urllib.URL) ?http.Response { fn send(req &string) ?http.Response {
req := '$method $url.request_uri() HTTP/1.1\nHost: localhost\n\n'
// Open a connection to the socket // Open a connection to the socket
mut s := unix.connect_stream(docker.socket) ? mut s := unix.connect_stream(docker.socket) ?
defer { defer {
// This or is required because otherwise, the V compiler segfaults for // This or is required because otherwise, the V compiler segfaults for
// some reason // some reason
// https://github.com/vlang/v/issues/13534
s.close() or {} s.close() or {}
} }
@ -42,8 +42,43 @@ fn request(method string, url urllib.URL) ?http.Response {
// Decode chunked response // Decode chunked response
return http.parse_response(res.bytestr()) return http.parse_response(res.bytestr())
}
fn request_with_body(method string, url urllib.URL, body &string) ?http.Response {
req := '$method $url.request_uri() HTTP/1.1\nHost: localhost\nContent-Length: ${body.len}\n$body\n'
return send(req)
}
fn request(method string, url urllib.URL) ?http.Response {
req := '$method $url.request_uri() HTTP/1.1\nHost: localhost\n\n'
return send(req)
}
pub fn request_with_json<T>(method string, url urllib.URL, data T) ?http.Response {
body := json.encode(data)
println(body)
return request_with_body(method, url, body)
} }
fn get(url urllib.URL) ?http.Response { fn get(url urllib.URL) ?http.Response {
return request('GET', url) return request('GET', url)
} }
struct ImagePull {
from_image string [json: fromImage]
tag string
}
pub fn pull(image string, tag string) ?http.Response {
// data := ImagePull{
// from_image: image
// tag: tag
// }
// return request_with_json("POST", urllib.parse("/images/create") ?, data)
return request("POST", urllib.parse("/images/create?fromImage=$image&tag=$tag") ?)
}