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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)