Reading from the Commandline in Go

Reading from the Commandline

This post is a quick walkthrough of how to read input from Command line interface

Use Case

You want to build an app which needs to read user input for it's operation before proceeding with the code flow

Example

package main

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

func  main() {
    reader  := bufio.NewReader(os.Stdin)
    data, _, err  := reader.ReadLine()
    if err !=  nil {
        log.Fatal(err)
    }
    fmt.Printf("User input: %s\n", string(data))
}

What you need to understand is that Command line interface where user enters data is a stream, in this case it is a standard input stream through which our application can plugin to the data that is entered by the user.

We will use the Standard input as an input to the factory bufio.NewReader like so:

bufio.NewReader(os.Stdin)

The reader object that is returned by the above function can be used to read an entire line entered by the user, which essentially means that when a user needs to press enter for the buffered reader to read the entire line. That's pretty much it.

There are many other functions that could be used to read the data, refer to them in the documentation

No Comments Yet