Search code examples
socketscurlgodockerdocker-swarm

Is there a straight way to get html response from a unix socket in Go (like curl does)?


I need to create a docker (1.13) container that will be running as a service in a docker swarm to schedule jobs (like a swarm-wide crontab that performs 'docker exec' where needed). I'm a rather sysadmin guy and not really a coder, so I started doing it with with bash, curl and jq. It works, but there is definitely room for improvement.

To give you an idea of the mumbo-jumpo I'm dealing with, here are a few snippets of the calls I pass to the docker socket to find out where the services are running:

# Get local docker node ID:
curl -s --unix-socket /var/run/docker.sock http:/v1.26/info | jq -r '.Name + " " + .Swarm.NodeID'

# List swarm node ID's:
curl -s --unix-socket /var/run/docker.sock http:/v1.26/nodes | jq -r '.[] | .Description.Hostname + " " + .ID'

# List swarm services:
curl -s --unix-socket /var/run/docker.sock http:/v1.26/nodes | jq -r '.[] | .Description.Hostname + " " + .ID'

# List running tasks:
curl -s --unix-socket /var/run/docker.sock http:/v1.26/tasks | jq -r '.[] | select( .Status.State | contains("running")) | .NodeID + " " + .ServiceID + " " + .ID + " " + .Status.State'

I'd like to do it nicer with golang.

I understand how http.Get works when talking to a tcp socket:

res, err := http.Get(url)
body, err := ioutil.ReadAll(res.Body)
err = json.Unmarshal(body, &p)
// p is then populated with the content of my request

But how can I deal with a unix filesocket (/var/run/docker.sock)? I assume I have to use net.DialUnix but could not get it to work so far.

Any idea or suggestion are welcome.


Solution

  • Try this:

    package main
    
    import (
        "fmt"
        "net"
        "log"
        "bufio"
    
    )
    
    func main() {
        conn, err := net.Dial("unix", "/var/run/docker.sock")
    
        if err != nil {
            panic(err)
        }
        fmt.Fprintf(conn, "GET /images/json HTTP/1.0\r\n\r\n")
        status, err := bufio.NewReader(conn).ReadString('\t')
        if err != nil {
            log.Println(err)
        }
    
        fmt.Print("Message from server: "+status)
    }
    

    Another approach:

    Use docker SDK, available for python, go and some other languages.