Skip to content

Instantly share code, notes, and snippets.

@flowerinthenight
Created September 18, 2018 03:33
Show Gist options
  • Save flowerinthenight/447f983882720d817f3b92088f98aaa3 to your computer and use it in GitHub Desktop.
Save flowerinthenight/447f983882720d817f3b92088f98aaa3 to your computer and use it in GitHub Desktop.
package main
import (
goflag "flag"
"github.com/golang/glog"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
)
var (
rootCmd = &cobra.Command{
Long: "Use glog with cobra.",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// For cobra + glog flags. Available to all subcommands.
goflag.Parse()
},
}
s1 string
s2 string
)
func init() {
rootCmd.AddCommand(
subCmd1(),
subCmd2(),
)
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
}
func subCmd1() *cobra.Command {
c := &cobra.Command{
Use: "sub1",
Short: "test subcmd1",
Long: "Test sub command 1.",
Run: func(cmd *cobra.Command, args []string) {
glog.Infof("hello %v from subCmd1", s1)
},
}
c.Flags().SortFlags = false
c.Flags().StringVar(&s1, "target", "world", "say hello to")
return c
}
func subCmd2() *cobra.Command {
c := &cobra.Command{
Use: "sub2",
Short: "test subcmd2",
Long: "Test sub command 2.",
Run: func(cmd *cobra.Command, args []string) {
glog.Infof("hello %v from subCmd2", s2)
},
}
c.Flags().SortFlags = false
c.Flags().StringVar(&s2, "target", "parallel world", "say hello to")
return c
}
func main() {
err := rootCmd.Execute()
if err != nil {
glog.Error(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment