Skip to content

Instantly share code, notes, and snippets.

@ericchiang
Last active August 29, 2015 14:10
Show Gist options
  • Save ericchiang/c988d90edcb7eebd54de to your computer and use it in GitHub Desktop.
Save ericchiang/c988d90edcb7eebd54de to your computer and use it in GitHub Desktop.
Docker remote api example
package main
import (
"archive/tar"
"bytes"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"github.com/docker/docker/utils"
)
var dockerfile = `FROM debian:jessie
RUN touch hello.txt`
func Compress(dockerfile string) (io.Reader, error) {
b := bytes.NewBuffer([]byte{})
tw := tar.NewWriter(b)
hdr := &tar.Header{
Name: "Dockerfile",
Size: int64(len(dockerfile)),
}
if err := tw.WriteHeader(hdr); err != nil {
return nil, err
}
if _, err := tw.Write([]byte(dockerfile)); err != nil {
return nil, err
}
if err := tw.Close(); err != nil {
return nil, err
}
return b, nil
}
func main() {
must := func(err error) {
if err != nil {
log.Fatal(err)
}
}
endpoint := "unix:///var/run/docker.sock"
u, err := url.Parse(endpoint)
must(err)
path := "/build"
zipped, err := Compress(dockerfile)
must(err)
req, err := http.NewRequest("POST", path, zipped)
must(err)
req.Header.Set("Content-Type", "application/tar")
dial, err := net.Dial(u.Scheme, u.Path)
must(err)
defer dial.Close()
conn := httputil.NewClientConn(dial, nil)
resp, err := conn.Do(req)
must(err)
defer resp.Body.Close()
io.Copy(os.Stderr, resp.Body)
utils.DisplayJSONMessagesStream(resp.Body, os.Stdout, os.Stdout.Fd(), true)
}
package main
import (
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"time"
)
type JSONTime time.Time
func (t *JSONTime) UnmarshalJSON(b []byte) error {
i, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return err
}
*t = JSONTime(time.Unix(i, 0))
return nil
}
type dockerImage struct {
RepoTags []string
Created JSONTime
Id string
Size int
VirtualSize int
}
func dockerImages(endpoint string) ([]dockerImage, error) {
images := []dockerImage{}
u, err := url.Parse(endpoint)
if err != nil {
return images, err
}
path := "/images/json?all=1"
req, err := http.NewRequest("GET", path, nil)
if err != nil {
return images, err
}
dial, err := net.Dial(u.Scheme, u.Path)
if err != nil {
return images, err
}
defer dial.Close()
conn := httputil.NewClientConn(dial, nil)
resp, err := conn.Do(req)
if err != nil {
return images, err
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(&images)
return images, err
}
func main() {
images, err := dockerImages("unix:///var/run/docker.sock")
if err == nil {
for i := range images {
fmt.Println(images[i])
}
} else {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment