Skip to content

Instantly share code, notes, and snippets.

@jecolasurdo
Created December 4, 2021 05:27
Show Gist options
  • Save jecolasurdo/17820d4a79f079adf4273ce3690a0dc9 to your computer and use it in GitHub Desktop.
Save jecolasurdo/17820d4a79f079adf4273ce3690a0dc9 to your computer and use it in GitHub Desktop.
A function for CLI prompt options
package clistuff
import (
"bufio"
"fmt"
"net/url"
"os"
"strings"
)
type PromptOptions struct {
Choices []string
SecretChoices []string
PromptMsg string
FailMsg string
}
func Prompt(options PromptOptions) string {
result := ""
scanner := bufio.NewScanner(os.Stdin)
inputText := fmt.Sprintf("%v {%v}: ", options.PromptMsg, strings.Join(options.Choices, ","))
fmt.Print(inputText)
scanLoop:
for scanner.Scan() {
text := scanner.Text()
for _, choice := range options.Choices {
if text == choice {
result = choice
break scanLoop
}
}
for _, choice := range options.SecretChoices {
if text == choice {
result = choice
break scanLoop
}
}
fmt.Println(options.FailMsg)
fmt.Print(inputText)
}
return result
}
func MustURL(rawURL string) *url.URL {
result, err := url.Parse(rawURL)
if err != nil {
panic(err)
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment