Skip to content

Instantly share code, notes, and snippets.

@nasum
Last active July 26, 2019 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasum/ae507d8069737a35e71615fe89b6d75a to your computer and use it in GitHub Desktop.
Save nasum/ae507d8069737a35e71615fe89b6d75a to your computer and use it in GitHub Desktop.
Goでコマンドラインツールを作るときの鉄板ライブラリ ref: https://qiita.com/nasum/items/f1911894802a2b92dc9e
$ go run main.go
root command
$ go run main.go --help
command line calculator
Usage:
culc [flags]
Flags:
-h, --help help for culc
$ go run main.go help
command line calculator
Usage:
culc [flags]
culc [command]
Available Commands:
help Help about any command
sum sum culc
Flags:
-h, --help help for culc
Use "culc [command] --help" for more information about a command.
$ go run main.go sum 1 1
2
green := color.New(color.FgGreen).SprintFunc()
fmt.Println(green(itemOne + itemTwo))
package main
import (
"fmt"
"os"
"github.com/nasum/culc/cmd"
)
func main() {
if err := cmd.RootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", os.Args[0], err)
os.Exit(-1)
}
}
func init() {
cobra.OnInitialize()
RootCmd.AddCommand(
sumCmd(),
)
}
package cmd
import (
"fmt"
"log"
"strconv"
"github.com/spf13/cobra"
)
func sumCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "sum",
Short: "sum culc",
Args: cobra.RangeArgs(2, 2),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return nil
}
itemOne, err := strconv.Atoi(args[0])
if err != nil {
log.Fatal(err)
return nil
}
itemTwo, err := strconv.Atoi(args[1])
if err != nil {
log.Fatal(err)
return nil
}
fmt.Println(itemOne + itemTwo)
return nil
},
}
return cmd
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment