Skip to content

Instantly share code, notes, and snippets.

@hiyosi
Last active July 24, 2017 12:26
Show Gist options
  • Save hiyosi/2395c7222461e61f6255bb1e60bbc265 to your computer and use it in GitHub Desktop.
Save hiyosi/2395c7222461e61f6255bb1e60bbc265 to your computer and use it in GitHub Desktop.
package cmd
import (
"errors"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
)
func NewCommandSample(out, errOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "sample",
Short: "A brief description of your command",
Run: func(cmd *cobra.Command, args []string) {
if err := RunSample(out, errOut, cmd, args); err != nil {
fmt.Fprint(errOut, "Failed to execute cmd: ", err)
os.Exit(1)
}
},
}
return cmd
}
func init() {
out := os.Stdout
errOut := os.Stderr
RootCmd.AddCommand(NewCommandSample(out, errOut))
}
func RunSample(out, errOut io.Writer, cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("Wrong number of arguments\n")
}
if args[0] != "hiyosi" {
return fmt.Errorf("unexpected arguments specified: %v", args[0])
}
fmt.Fprintf(out, "Hello %v, This is a sample", args[0])
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment