go命令行工具制作模板
一个快速制作go工具的模板, 可接收外部入参的
package main
import (
"flag"
"fmt"
"log"
"os"
)
const OSEXIT2 = 2
var (
help1 *bool
help2 *bool
para1 *string
para2 *string
)
type config struct {
para1 string
para2 string
}
func init() {
help1 = flag.Bool("h", false, "help")
help2 = flag.Bool("help", false, "help")
para1 = flag.String("para1", "", " use para1")
para2 = flag.String("para2", "", " use para2")
}
func usage() {
fmt.Fprintf(os.Stderr, "usage of tool\n")
flag.PrintDefaults()
os.Exit(OSEXIT2)
}
func parse() *config {
flag.Usage = usage
flag.Parse()
cfg := &config{}
cfg.para1 = *para1
cfg.para2 = *para2
if *help1 || *help2 {
flag.Usage()
}
return cfg
}
func main() {
log.SetPrefix("[run tool]")
cfg := parse()
log.Printf("para1: %v, para2: %v\n", cfg.para1, cfg.para2)
}
用go build可制作出可执行文件
用结构体config承载入参
参数输入-h或者-help可打印出用法