简体   繁体   中英

golang Infinite for loop problem with docker run

I tried to do simple infinite for loop task. It is working fine without using docker. But when i used the docker,it only executes the else part of for loop infinitely. What may be problem actually? Is docker having problem with infinite for loop? My main.go file is shown below.

package main

 import (
"bufio"
"fmt"
"os"
 )

func main() {
 fmt.Println("Hello, World!.....")

 for {
    fmt.Print("-> ")
    var i int
    fmt.Scan(&i)
    if i == 1 {
        fmt.Println("Hello, World! 1")
    } else if i == 2 {

        fmt.Println("Hello, World! 2")
    } else if i == 3 {
        fmt.Println("Hello, World! 3")
    } else if i == 4 {
        fmt.Println("Hello, World! 4")
    } else if i == 5 {
        fmt.Println("Hello, World! 5")
    } else {
        fmt.Println("Hello, World! else")
        
    }

 }
}

I tried these link as well. Read line in golang How do I break out of an infinite loop in Golang But still of no use. I am trying to solve the problem since yesterday.

The docker file is as given below:

FROM golang:1.12.0-alpine3.9

RUN mkdir /app

ADD . /app

WORKDIR /app

RUN go build -o main .

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

I tried to build the docker using docker build -t hello. and run using docker run hello

Running with

docker run hello

我尝试使用 docker run hello 运行,它只会无限打印 else 部分

Executing with console without docker go run main.go 我尝试使用 go run main.go 运行,它工作正常

The infinite loop is because your go program is waiting for an input and you're not launching the container in interactive mode.

To make it work you need to use this command (note the -it option):

docker container run --rm --name hello -it hello

Scan returns an error. It is likely that no data is read and i is 0 (as that is the zero value of an int ).

Change your code to panic in case of no data:

var i int
_, err := fmt.Scan(&i)
if err != nil {
    panic(err)
}

The Go playground behaves in a similar way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM