1.3命令行参数获取 flag
package main
import (
"flag"
"fmt"
"log"
"os"
"strings"
)
// Custom type need to implement
// flag.Value interface to be able to
// use it in flag.Var function.
type ArrayValue []string
func (s *ArrayValue) String() string {
return fmt.Sprintf("%v", *s)
}
func (a *ArrayValue) Set(s string) error {
*a = strings.Split(s, ",")
return nil
}
func main() {
// Extracting flag values with methods returning pointers
retry := flag.Int("retry", -1, "Defines max retry count")
// Read the flag using the XXXVar function.
// In this case the variable must be defined
// prior to the flag.
var logPrefix string
flag.StringVar(&logPrefix, "prefix", "", "Logger prefix")
var arr ArrayValue
flag.Var(&arr, "array", "Input array to iterate through.")
// Execute the flag.Parse function, to
// read the flags to defined variables.
// Without this call the flag
// variables remain empty.
flag.Parse()
// Sample logic not related to flags
logger := log.New(os.Stdout, logPrefix, log.Ldate)
retryCount := 0
for retryCount < *retry {
logger.Println("Retrying connection")
logger.Printf("Sending array %v\n", arr)
retryCount++
}
}
/*
./go_web -h
Usage of ./go_web:
-array value
Input array to iterate through.
-prefix string
Logger prefix
-retry int
Defines max retry count (default -1)
*/
/*
./go_web -retry 1 -prefix=test -array=dssd,11,3453
test2018/03/17 Retrying connection
test2018/03/17 Sending array [dssd 11 3453]
*/
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步