41 lines
658 B
Go
41 lines
658 B
Go
package input
|
|
|
|
import (
|
|
"bufio"
|
|
"os"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// Validator represent signature of the input validation function.
|
|
type Validator func(in string) (string, error)
|
|
|
|
// Ask will ask user for an input and check validity with provided fn function.
|
|
func Ask(mandatory bool, fn Validator) string {
|
|
scanner := bufio.NewScanner(os.Stdin)
|
|
for {
|
|
|
|
scanner.Scan()
|
|
userInput := scanner.Text()
|
|
|
|
if userInput == "" {
|
|
|
|
if mandatory {
|
|
log.Warn("Empty input, try again")
|
|
continue
|
|
}
|
|
|
|
return userInput
|
|
}
|
|
|
|
value, err := fn(userInput)
|
|
|
|
if err != nil {
|
|
log.Warnf("%s", err.Error())
|
|
continue
|
|
}
|
|
|
|
return value
|
|
}
|
|
}
|