Created
December 2, 2015 10:08
-
-
Save djui/79a65ee3a5663da499ba to your computer and use it in GitHub Desktop.
Minimal readline with timeout example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
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
You can also use
bufio.NewScanner()
and grabsc.Text()
.