Search code examples
goprompt

How to ask "Yes" or "No" using Golang


I'm using promptUi to create a select list. Now I want to prompt a "Yes" or "No" question after a selection:

bold := color.New(color.Bold).SprintFunc()
cellTemplate := &promptui.SelectTemplates{
    Label:    "{{ . }}",
    Active:   "\U000027A4 {{ .| bold }}",
    Inactive: "  {{ . | faint }}",
    Help:     util.Faint("[Use arrow keys]"),
}

cellPrompt := promptui.Select{
    Label:     util.YellowBold("?") + " Select an environment to be installed",
    Items:     getCreateEnvironmentList(),
    Templates: cellTemplate,
}
_, value, err := cellPrompt.Run()
if err != nil {
    return fmt.Errorf("Failed to select: %v", err)
}

switch value {
case constants.CELLERY_CREATE_LOCAL:
    {
        // Prompt yes or no
    }
case constants.CELLERY_CREATE_GCP:
    {
        // Prompt yes or no
    }
default:
    {
        Back()
    }
}

Is there a similar way to prompt that in an elegant way?


Solution

  • Try this func yesNo() bool:

    package main
    
    import (
        "fmt"
        "log"
    
        "github.com/manifoldco/promptui"
    )
    
    func main() {
        fmt.Println(yesNo())
        fmt.Println(yesNo())
    
    }
    func yesNo() bool {
        prompt := promptui.Select{
            Label: "Select[Yes/No]",
            Items: []string{"Yes", "No"},
        }
        _, result, err := prompt.Run()
        if err != nil {
            log.Fatalf("Prompt failed %v\n", err)
        }
        return result == "Yes"
    }
    

    Output:

    ? Select[Yes/No]: 
      ▸ Yes
        No
    
    ✔ Yes
    true
    ✔ No
    false