I'm building an golang app to upload some docs to a webserver. The app is a single go file called deploy_docs.go
(run make build
to build the application).
I'm somewhat new to go, so please keep that in mind if this is a dumb question ;-).
The app should be called like this:
bin/deploy_docs --dochost foo.bar.local
I am parsing CLI arguments in buildAppInstance()
, which should assign the CLI value of --dochost
to &dochost
in buildAppInstance()
.
The problem is that I never get anything assigned to &dochost
; I'm not sure why... I don't think this is scope problem but I don't know how urfave/cli
should work otherwise.
Can someone explain why &dochost
never gets populated by --dochost
?
You should call (*App).Run to make it parse arguments. See the demo below:
package main
import (
"log"
"os"
"time"
"github.com/urfave/cli/v2"
)
var dochost string = ""
func buildAppInstance() (appInst *cli.App) {
appInst = &cli.App{
Name: "deploy_docs",
Version: "0.0.2",
Compiled: time.Now(),
Authors: []*cli.Author{
{
Name: "Mike Pennington",
Email: "[email protected]",
},
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "dochost",
Value: "127.0.0.1",
Usage: "FQDN or IPv4 of the documentation host",
Destination: &dochost,
},
},
Action: func(cCtx *cli.Context) (err error) {
log.Println("Starting cli.Context action")
if cCtx.NArg() == 0 {
log.Fatal("No CLI arguments detected!")
}
log.Printf("args: %+v", cCtx.Args())
return nil
},
}
return appInst
}
func main() {
app := buildAppInstance()
log.Printf("dochost before Run: %q", dochost)
if err := app.Run(os.Args); err != nil {
panic(err)
}
log.Printf("dochost after Run: %q", dochost)
}
$ go run . --dochost foo.bar.local other args
2023/06/26 23:37:43 dochost before Run: ""
2023/06/26 23:37:43 Starting cli.Context action
2023/06/26 23:37:43 args: &[other args]
2023/06/26 23:37:43 dochost after Run: "foo.bar.local"