Created
December 4, 2021 05:27
-
-
Save jecolasurdo/17820d4a79f079adf4273ce3690a0dc9 to your computer and use it in GitHub Desktop.
A function for CLI prompt options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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