dqf98772 2018-01-22 23:42
浏览 467
已采纳

如何通过WebSocket获取Docker容器输出?


I am trying to send output from a docker container to the console using fmt, but when trying to do it i get this.

&{0xc0422a65c0 {0 0} false <nil> 0x6415a0 0x641540}

How do I do this? This is my full code.

func main() {
    imageName := "hidden/hidden"

ctx := context.Background()

cli, err := client.NewClient("tcp://0.0.0.0:0000", "v0.00", nil, nil)
if err != nil {
    panic(err)
}

fmt.Println("Pulling \"" + imageName + "\"")
_, err = cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
if err != nil {
    panic(err)
}

containerConfig := &container.Config{
    Image: imageName,
    Cmd: []string{"./app/start.sh", "--no-wizard"},
}

resp, err := cli.ContainerCreate(ctx, containerConfig, nil, nil, "")
if err != nil {
    panic(err)
}

if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
    panic(err)
}

timer := time.NewTimer(time.Minute)
go func() {
    <-timer.C
    if err := cli.ContainerStop(ctx, resp.ID, nil); err != nil {
        panic(err)
    }
}()

out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true, ShowStderr: true, Follow: true})
if err != nil {
    panic(err)
}

io.Copy(os.Stdout, out) // This is what I want to change to print with "fmt".
}

Tried: (but does not display until container is done.)

buf := new(bytes.Buffer)
buf.ReadFrom(out)
fmt.Println(buf.String())

Intention: Allow real-time console output to the web.

  • 写回答

2条回答 默认 最新

  • duancenxie2233 2018-01-23 13:52
    关注

    This seems to be the answer to my question, I did some searching about scanners as Cerise Limón commented. Anyone else who seems to be having the issue that I did can use this code. Thanks to all that helped.

    scanner := bufio.NewScanner(out)
    scanner.Split(bufio.ScanLines)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试