Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use os.Args in golang?

I need to use config in my go code and I want to load config path from command-line. I try:

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 launch my go file with parameter (or without) I receive similar error

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

How should I correctly use os.Args?

like image 721
Dmitriy Demidov Avatar asked Apr 21 '14 08:04

Dmitriy Demidov


Video Answer


2 Answers

Define configPath outside the scope of your if.

configPath := ""

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

Note the 'configPath =' (instead of :=) inside the if.

That way configPath is defined before and is still visible after the if.

See more at "Declarations and scope" / "Variable declarations".

like image 65
VonC Avatar answered Oct 01 '22 17:10

VonC


For another approach, you can wrap the logic in a function:

package main
import "os"

func configPath(a []string) string {
   switch len(a) {
      case 1: return "/etc/buildozer/config"
      default: return os.Args[1]
   }
}

func main() {
   config := configPath(os.Args)
   println(config)
}

this avoids the scoping issue.

like image 24
Zombo Avatar answered Oct 01 '22 16:10

Zombo