How to use os.Args in golang properly?

I need to use config in my go code, and I want to load the configuration path from the command line. I'm trying to:

if len(os.Args) > 1 { 
        configpath := os.Args[1]
        fmt.Println("1") // For debug
    } else {
        configpath := "/etc/buildozer/config"
        fmt.Println("2")
    }

Then I use config:

configuration := config.ConfigParser(configpath)

When I run my go file with or without a parameter, I get a similar error

# command-line-arguments
src/2rl/buildozer/buildozer.go:21: undefined: configpath

How to use os.Args correctly?

+4
source share
1 answer

Define configPathout of scope if.

configPath := ""

if len(os.Args) > 1 { 
  configpath = os.Args[1] 
  fmt.Println("1") // For debug 
} else { 
  configpath = "/etc/buildozer/config"
  fmt.Println("2") 
}

Note the " configPath =" (instead :=) inside if.

Thus, it configPathis determined before and remains visible after if.

"/" ".

+7

Source: https://habr.com/ru/post/1537339/


All Articles