Having some basic features on Go

As a Python and Django developer, I can run any part of the code in my project using a script independently.

I'm not too sure how to achieve the same thing in Go, since it seems like every Go project should have only one main executable.

I would like to call a function in my project from cronjob, but I'm not too sure how to add this. Using flags in my main function is the only way I can do this. But this will look rather confusing if my script accepts additional flags on its own, as shown below:

go run server.go --debug --another-flag --script-name <MY-SCRIPT> --my-script-flag-one <FLAG-ONE> --my-script-flag-two <FLAG-TWO> 

Is there an elegant way to do this?

+6
source share
1 answer

I refer to “ What is a smart way to build a Go project :“ Structuring applications in Go, ”which shows an example camlistore . <w> This project includes several cmd packages , each of which has its own set of parameters.

Another option is to use a CLI library such as spf13/cobra , which allows you to define several commands (the same thing, separate sets of options).

Command is the central point of the application.
Each interaction supported by the application will be contained in Command .
A command may have child commands and optionally trigger an action.

In the example " hugo server --port=1313 ", " server " is a command

A Command has the following structure:

 type Command struct { Use string // The one-line usage message. Short string // The short description shown in the 'help' output. Long string // The long message shown in the 'help <this-command>' output. Run func(cmd *Command, args []string) // Run runs the command. } 
+6
source

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


All Articles