gouick/helpers/input/input.go
Matthieu 'JP' DERASSE dccbb30a85
All checks were successful
continuous-integration/drone/push Build is passing
feat(input): Full refacto of the user input system
2022-09-16 20:22:19 +00:00

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