gouick/helpers/input/input.go

41 lines
658 B
Go
Raw Normal View History

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
}
}