Skip to content

Simple library for read commands from stdin for golang

License

Notifications You must be signed in to change notification settings

nessai1/gocommand

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

imageimage

gocommand

GitHub go.mod Go version GitHub GoDoc

Gocommand is the simplest way to create a command line interface throw stdin/out for your Go application. It provides a simple way to read commands and arguments from the standard input and execute them.

Usage

Simple command read

package main

import (
	"fmt"
	"github.com/nessai1/gocommand"
)

func main() {
	gocommand.ListenAndServe(func(cmd *gocommand.Command) error {
		if cmd.Name == "exit" {
			return gocommand.ErrGracefulExit
		}

		fmt.Printf("Command: %s\n", cmd.Name)
		fmt.Printf("Arguments: %v\n", cmd.Args)

		return nil
	})
}

Output:
shell_example_1

Prompting the user for input

Library allows you to ask user for input using the AskText and AskSecret functions

  • AskText function asks the user for a text input and returns it as a string
  • AskSecret function asks the user for a sensitive data and returns it as a string
package main

import (
	"fmt"
	"github.com/nessai1/gocommand"
)

func main() {
	gocommand.ListenAndServe(func(cmd *gocommand.Command) error {
		if cmd.Name == "exit" {
			return gocommand.ErrGracefulExit
		}

		if cmd.Name == "login" {
			login, err := gocommand.AskText("Enter your username")
			if err != nil {
				return fmt.Errorf("cannot ask login: %w", err)
			}

			password, err := gocommand.AskSecret("Enter your password")
			if err != nil {
				return fmt.Errorf("cannot ask password: %w", err)
			}

			fmt.Printf("make authentification with login '%s' and password '%s'...\n", login, password)
		}

		return nil
	})
}

Output:
shell_example_1

About

Simple library for read commands from stdin for golang

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages