"3 state"命令行参数在Go语言中的实现

huangapple go评论76阅读模式
英文:

"3 state" command line arguments in Go

问题

我正在编写一个需要访问互联网的应用程序。对于一些主机,连接需要通过代理进行。我知道代理可以在环境变量中设置,但我想从应用程序本身进行设置。
我需要一个命令行参数,可以以三种不同的方式使用:

  1. 完全不给出 -> 不使用代理
  2. --use-proxy -> 使用默认代理
  3. --use-proxy "http://my-proxy.com:880" -> 使用给定的代理

以下使用默认或给定的地址,但不能用于忽略代理:
> use_proxy := flag.String("use-proxy", "http://my-proxy.com:880", "使用代理...")

这个只实现了第1和第2点:

use_proxy := flag.Bool("use-proxy", false , "使用代理...")
if *use_proxy {
...
proxyUrl, err := url.Parse("http://my-proxy.com:880")
...
}

这个问题可以通过两个标志来解决,但我宁愿只使用一个:
> myapp --use-proxy --proxy "http://my-proxy.com:880"

英文:

I'm writing an application that needs access to Internet. From some hosts the connection needs to go through proxy. I know that proxy can be set on an environment variable, but I want to do it from the application itself.
I need a command line argument that can be used in three different ways:

  1. not given at all -> no proxy
  2. --use-proxy -> use default proxy
  3. --use-proxy "http://my-proxy.com:880" -> uses given proxy

Following uses default or given address but cannot be used to ignore proxy:
> use_proxy := flag.String("use-proxy", "http://my-proxy.com:880", "Use proxy...")

This one accomplishes only points 1 & 2:

use_proxy := flag.Bool("use-proxy", false , "Use proxy...")
if *use_proxy {
  ...
  proxyUrl, err := url.Parse("http://my-proxy.com:880")
  ...
}

The problem could be solved with two flags but I'd rather use just one:
> myapp --use-proxy --proxy "http://my-proxy.com:880"

答案1

得分: 3

如果您的应用程序绝对不会使用任何其他命令行参数,那么您可以将--use-proxy设置为布尔标志,然后从第一个命令行参数(即os.Args)获取代理URL。

从长远来看,这可能不是一个好主意,因为它限制了向程序添加其他参数/选项的能力。

大多数参数解析器不会处理这种情况,因为它使解析命令行选项变得模糊不清。

其他选项可能是允许使用默认值的关键字,例如:

myapp --use-proxy "http://my-proxy.com:880"
myapp --use-proxy default

或者使用两个选项,两者都启用代理,但只有一个带有参数,例如:

myapp --use-proxy <proxy URL>
myapp --use-default-proxy
英文:

If your app definitely won't use any other command line arguments, then you can just make --use-proxy a boolean flag, and then get the proxy URL from the first command line argument, i.e. from os.Args.

This probably isn't a good idea long term though, as it restricts adding additional arguments/options to your program.

Most argument parsers won't handle a case like this, since it makes parsing command line options ambiguous.

Other options could be to allow a keyword for the default value, e.g.:

myapp --use-proxy &quot;http://my-proxy.com:880&quot;
myapp --use-proxy default

or to use two options, both of which enable the proxy, but having only one take an argument, e.g.:

myapp --use-proxy &lt;proxy URL&gt;
myapp --use-default-proxy

huangapple
  • 本文由 发表于 2013年3月26日 17:12:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/15633161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定