jessevdk/go-flags

Env variables totally bypass flag type validation

OStrekalovsky opened this issue · 0 comments

If the program will be configured only via env variables (very popular for docker containers), provided values for env variables will bypass all type convertations and results in default values for this variables types. If these values are specified through the program arguments and the type values are incorrect, the user as expected will receive an error. Suppose that it is related with #309

Example:

package main

import (
	"github.com/jessevdk/go-flags"
	"log"
)

type Opts struct {
	Timeout int `long:"timeout" env:"TIMEOUT" default:"5"`
}

func main(){
	var opts Opts

	p := flags.NewParser(&opts, flags.Default)
	if _, err := p.Parse(); err != nil {
		log.Fatalf("error:%w",err)
	}
	log.Printf("timeout=%d", opts.Timeout)
}

Examples:
Correct:
env TIMEOUT=10 go run .
2020/01/28 12:40:28 timeout=10

Incorrect:
env TIMEOUT=xyz go run .
2020/01/28 12:40:34 timeout=0

Incorrect:
env TIMEOUT= go run .
2020/01/28 12:52:31 timeout=0

Correct:
go run . --timeout=
invalid argument for flag --timeout' (expected int): strconv.ParseInt: parsing "": invalid syntax 2020/01/28 12:54:19 error:%!w(*flags.Error=&{4 invalid argument for flag --timeout' (expected int): strconv.ParseInt: parsing "": invalid syntax})
exit status 1

Correct:
go run . --timeout=hyz
invalid argument for flag --timeout' (expected int): strconv.ParseInt: parsing "hyz": invalid syntax 2020/01/28 12:54:31 error:%!w(*flags.Error=&{4 invalid argument for flag --timeout' (expected int): strconv.ParseInt: parsing "hyz": invalid syntax})
exit status 1