Skip to content

Instantly share code, notes, and snippets.

@djui
Created December 2, 2015 10:08
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save djui/79a65ee3a5663da499ba to your computer and use it in GitHub Desktop.
Save djui/79a65ee3a5663da499ba to your computer and use it in GitHub Desktop.
Minimal readline with timeout example
import (
"bufio"
"errors"
"strings"
"time"
)
// Readln reads and returns a single line (sentinal: \n) from stdin.
// If a given timeout has passed, an error is returned.
// This functionality is similar to GNU's `read -e -p [s] -t [num] [name]`
func Readln(prompt string, timeout time.Duration) ([]byte, error) {
s := make(chan string)
e := make(chan error)
go func() {
fmt.Print(prompt)
reader := bufio.NewReader(os.Stdin)
line, err := reader.ReadString('\n')
if err != nil {
e <- err
} else {
s <- line
}
close(s)
close(e)
}()
select {
case line := <-s:
return line, nil
case err := <-e:
return nil, err
case <-time.After(timeout):
return nil, errors.New("Timeout")
}
}
@iDuronto
Copy link

You can also use bufio.NewScanner() and grab sc.Text().

@RonaldinhoL
Copy link

reader.ReadString() seems never exit in this case

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment