-
-
Notifications
You must be signed in to change notification settings - Fork 369
Expand file tree
/
Copy pathquestion.go
More file actions
36 lines (32 loc) · 657 Bytes
/
question.go
File metadata and controls
36 lines (32 loc) · 657 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package comms
import (
"bufio"
"fmt"
"io"
"strings"
)
// Question provides an interactive session.
type Question struct {
Reader io.Reader
Writer io.Writer
Prompt string
DefaultValue string
}
// Read reads the user's input.
func (q Question) Read(r io.Reader) (string, error) {
reader := bufio.NewReader(r)
s, err := reader.ReadString('\n')
if err != nil {
return "", err
}
s = strings.TrimSpace(s)
if s == "" {
return q.DefaultValue, nil
}
return s, nil
}
// Ask displays the prompt, then records the response.
func (q *Question) Ask() (string, error) {
fmt.Fprintf(q.Writer, q.Prompt)
return q.Read(q.Reader)
}