How to get user input in Docker with Go

huangapple go评论87阅读模式
英文:

How to get user input in Docker with Go

问题

main.go

package main

import (
	"bufio"
	"os"
	"time"
)

func main() {
	code, err := bufio.NewReader(os.Stdin).ReadString('\n')
	if err != nil {
		panic(err)
	}
	time.Sleep(time.Second * 10)
}

Dockerfile

FROM golang:1.17

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY . /usr/src/app

CMD ["go","run","main.go"]

创建并运行 Docker 容器时出现错误,如下图所示:

How to get user input in Docker with Go

我想在运行 Docker 容器时从终端获取用户输入。

英文:

main.go

package main

import (
	"bufio"
	"os"
	"time"
)

func main() {
	code, err := bufio.NewReader(os.Stdin).ReadString('\n')
	if err != nil {
		panic(err)
	}
	time.Sleep(time.Second * 10)
}

Dockerfile

FROM golang:1.17

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY . /usr/src/app


CMD ["go","run","main.go"]

When create docker container and run it get and error like it:

How to get user input in Docker with Go

I want to get user input from terminal when run docker container

答案1

得分: 1

通过使用ENTRYPOINT而不是CMD,您的用户可以在docker run命令之后传递参数:

ENTRYPOINT ["echo", "Hello World"]

docker run <container-name>
> Hello World
docker run <container-name> test
> Hello World test

但是,您应该使用os.Args来检索这些参数。

英文:

By using ENTRYPOINT instead of CMD your user could pass parameters after the docker run command:

ENTRYPOINT [&quot;echo&quot;, &quot;Hello World&quot;]

docker run &lt;container-name&gt;
&gt; Hello World
docker run &lt;container-name&gt; test
&gt; Hello World test

However you should use os.Args to retrieve those argument.

huangapple
  • 本文由 发表于 2022年3月3日 20:11:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/71337018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定