godvlpr
godvlpr

Reputation: 161

Set flag to golang request

I have a CURL string curl --unix-socket /var/run/docker.sock http://localhost/containers/json It has a flag --unix-sock How can i set this flag to http request in golang?

Upvotes: 4

Views: 519

Answers (1)

Peter
Peter

Reputation: 31691

Use the DialContext field of http.Transport to connect to unix sockets (most error handling omitted for brevity):

package main

import (
    "context"
    "fmt"
    "log"
    "net"
    "net/http"
    "net/http/httputil"
)

func main() {
    c := &http.Client{
        Transport: &http.Transport{
            DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
                return (&net.Dialer{}).DialContext(ctx, "unix", "/var/run/docker.sock")
            },
        },
    }

    req, _ := http.NewRequest("GET", "http://localhost/containers/json", nil)

    res, err := c.Do(req)
    if err != nil {
        log.Fatal(err)
    }

    b, _ := httputil.DumpResponse(res, true)
    fmt.Println(string(b))
}

Upvotes: 4

Related Questions