43

golang flag redefined错误

 4 years ago
source link: https://www.tuicool.com/articles/IV3eYrv
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

因为之前命令行参数是同过os.Args[1]来获取,感觉不太科学也不美观,所以今天改用flag去获取。

原始代码如下:

func GetRuntimePath() string {
    var spath string
    flag.StringVar(&spath, "p", " ", "这里请务必传入项目根目录")
    flag.Parse()
    return spath
}

结果go run 时报错,flag redefined: p。

框架使用的iris mvc框架,在router中调用了一次,另外在xorm engine的实例化方法里面获取config文件时也调用了一次。也就是说,在程序中 多次调用了GetRuntimePath方法

flag是不能多次调用的,所以,这里加多一个缓存。

var Staticpath string

func GetRuntimePath() string {
    if Staticpath != "" {
        return Staticpath
    }
    var spath string
    flag.StringVar(&spath, "p", " ", "这里请务必传入项目根目录")
    flag.Parse()
    Staticpath = spath
    return Staticpath
}

因为这个命令行获取的参数获取到之后就不会再发生变动,所以我们使用包全局变量保存起来,第一次访问的时候从命令行获取,再次访问直接就拿全局变量的值即可,这样也不会再次出发flag的方法调用。完美解决问题。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK