如何在其他包中获取标志参数

I write program in go, and I have a problem with get variable form command line in other own package using package flag .

flag.Parse()

Main problem is in Configuration package, because I use her many times in many places, so I want to avoid pass pionter to her, and I decided create as an independent module. Now I have problem with get flag to pathFile with configuration. My code looks like below

I run my program with parameter

program -config=/my/path/config.cfg

and main function

func main() {
        flag.Parse()
      // some next operation but not with configuration Type
      // the type of configuration is use in other object 
      //and in other place in my program
      //  here I only want to parse plag from
      // cmd lines
}

package configuration and file configuration.go so configuration/configuration.go

var (
    configPath string
    C          *configuration
)

func init() {
    flag.StringVar(&configPath,
        "config",
        "/defaultpath/config.gcfg",
        "Path to configuration file")
    C = &configuration{}
    if err := gcfg.ReadFileInto(C, configPath); err != nil {
        fmt.Printf("Cannot read configuration file. Program was Terminated error:%s", err)
        os.Exit(1)
    }
}

type configuration struct {
    Queue struct {
        User                    string
        Host                    string
        Port                    string
}

After compilation I get error: Cannot open log file error:open /defaultpath/config.gcfg: no such file or directory. Program was terminated.

As look above Parsed flags in main are not visible in package configuration, because configuration module try start with default path nor form arguments cmd line. that's why this must be finish error, because this path dosen't exist in my local machine

Question on end is: How export flag variable from main package to other own package ?

The init() in configuration is run before anything in main is executed, so there's no way the effect of flag.Parse() could be seen. You also need to declare the flag variables before you call flag.Parse()

You can't export anything from main, both because main can't be imported, and because you can't have a circular dependency between the packages. Have the main package call a function from the configuration package to get the behavior you want.

You could add an exported Init() function in configuration to handle the flag options:

func Init() {
    flag.StringVar(&configPath,
        "config",
        "/defaultpath/config.gcfg",
        "Path to configuration file")
    flag.Parse()

    C = &configuration{}
    if err := gcfg.ReadFileInto(C, configPath); err != nil {
        fmt.Printf("Cannot read configuration file. Program was Terminated error:%s", err)
        os.Exit(1)
    }
}

and have the main function start with

func main() {
        configuration.Init()
}