How to Read From Standard Input in Golang


Reading from “standard input” is really useful if you are making a command-line application and require user input.

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    s, _ := reader.ReadString('\n')
    fmt.Printf(s)
}

First setup a new bufio reader, then use ReadString function, with a default wait character, which we have set to a newline (\n).

The application will pause at this point and wait for user input before proceeding.