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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
package main
import (
"errors"
"fmt"
"log"
"strconv"
"github.com/charmbracelet/huh"
)
func main() {
var value string
defaultValue := 10
var chosen int
f := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Value(&value).
Title("Max").
Placeholder(strconv.Itoa(defaultValue)).
Validate(func(s string) error {
v, err := strconv.Atoi(value)
if err != nil {
return err
}
if v <= 0 {
return errors.New("maximum must be positive")
}
return nil
}).
Description("Select a maximum"),
huh.NewSelect[int]().
Value(&chosen).
Title("Pick a number").
DescriptionFunc(func() string {
v, err := strconv.Atoi(value)
if err != nil || v <= 0 {
v = defaultValue
}
return "Between 1 and " + strconv.Itoa(v)
}, &value).
OptionsFunc(func() []huh.Option[int] {
var options []huh.Option[int]
v, err := strconv.Atoi(value)
if err != nil {
v = defaultValue
}
for i := range v {
options = append(options, huh.NewOption(strconv.Itoa(i+1), i+1))
}
return options
}, &value),
),
)
err := f.Run()
if err != nil {
log.Fatal(err)
}
fmt.Println(chosen)
}
|