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:
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"
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 "http://my-proxy.com:880"
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 <proxy URL>
myapp --use-default-proxy