Created
October 26, 2018 20:05
-
-
Save jdaily/ae9640750d1d73170312963e720075d6 to your computer and use it in GitHub Desktop.
Interactive golang cli with promptui
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 main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"github.com/go-ozzo/ozzo-validation" | |
"github.com/go-ozzo/ozzo-validation/is" | |
"github.com/manifoldco/promptui" | |
"github.com/urfave/cli" | |
) | |
func promptUsername() (string, error) { | |
usernameValidate := | |
func(input string) error { | |
return validation.Validate(input, | |
validation.Required, // not empty | |
is.Email, // is a valid Email | |
) | |
} | |
userNamePrompt := promptui.Prompt{ | |
Label: "Username", | |
Validate: usernameValidate, | |
} | |
return userNamePrompt.Run() | |
} | |
func promptPassword() (string, error) { | |
passwordValidate := | |
func(input string) error { | |
return validation.Validate(input, | |
validation.Required, // not empty | |
validation.Length(5, 100), // length between 5 and 100 | |
) | |
} | |
passwordPrompt := promptui.Prompt{ | |
Label: "Password", | |
Validate: passwordValidate, | |
} | |
return passwordPrompt.Run() | |
} | |
func main() { | |
app := cli.NewApp() | |
app.Name = "interactive-cli" | |
app.Usage = "An interactive cli to type credentials" | |
app.Action = func(c *cli.Context) error { | |
fmt.Println("Login with a authorized user!") | |
name, err := promptUsername() | |
if err != nil { | |
fmt.Printf("Invalid Username %v \n", err) | |
} | |
pw, err := promptPassword() | |
if err != nil { | |
fmt.Printf("Invalid Password %v \n", err) | |
} | |
fmt.Printf("Sweet! %s, pw %s", name, pw) | |
return nil | |
} | |
err := app.Run(os.Args) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment