donglian4879 2017-03-06 22:42
浏览 67
已采纳

有没有一种直接的方法可以从Go中的unix套接字获取html响应(像curl一样)?

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.

  • 写回答

1条回答 默认 最新

  • duanhongyi2964 2017-03-07 08:05
    关注

    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
    
    ")
        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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题