Skip to content

Instantly share code, notes, and snippets.

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 ursuad/489d9cb5cacae9b95159cf11f5fcc679 to your computer and use it in GitHub Desktop.
Save ursuad/489d9cb5cacae9b95159cf11f5fcc679 to your computer and use it in GitHub Desktop.
# Source: https://flowerinthenight.com/blog/2019/02/05/golang-cobra-klog
package main
import (
goflag "flag"
"github.com/spf13/cobra"
flag "github.com/spf13/pflag"
"k8s.io/klog"
)
var (
str = "hello world"
rootCmd = &cobra.Command{
Use: "echo",
Short: "use klog with cobra",
Long: "Use klog together with cobra.",
}
)
func init() {
rootCmd.Flags().SortFlags = false
rootCmd.AddCommand(
RunCmd(),
)
klog.InitFlags(nil)
goflag.Parse()
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
}
func RunCmd() *cobra.Command {
runcmd := &cobra.Command{
Use: "run",
Short: "run command",
Long: "Run command.",
Run: func(cmd *cobra.Command, args []string) {
klog.Infof("echo=%v", str)
},
}
runcmd.Flags().SortFlags = false
runcmd.Flags().StringVar(&str, "str", str, "string to print")
return runcmd
}
func main() {
if err := rootCmd.Execute(); err != nil {
klog.Fatalf("root cmd execute failed, err=%v", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment