'Having multiple main functions on Go

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

I am not too sure how to achieve the same thing in Go, as it looks like each Go project should only have one main executable file.

I'd like to call a function in my project from cronjob, but I'm not too sure how to add that. Using flags in my main function is the only way I can think of doing this. But it will look pretty confusing if my script accepts additional flags by itself like the following:

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 any elegant way of doing this?



Solution 1:[1]

You can have multiple main function in go but the package should be declared main. This way you can have multiple go scripts/file inside package main where each file will have main function. To run a file, you can directly execute the file like go run file.go which will only execute the main function of file you called.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mayank Pant