Is main.go required in a Go project? - go

Without a background in C and only "beginner" experience in Go I'm trying to work out whether main.go is actually required or is just a convention.
I'm looking to create a simple web API but could someone clarify this for me?

main.go as a file is not required.
However, a main package with a func main() is required for executables.
Your file name can be called whatever you want.
E.g
myawesomeapp.go
package main
func main() {
fmt.Println("Hello World")
}
Running go run myawesomeapp.go will work as expected.

For a web server (an executable) you need to have a package main with a func main(), but it doesn't need to be called main.go - the file name can be anything you want it to be. From the language spec:
Program execution
A complete program is created by linking a single, unimported package
called the main package with all the packages it imports,
transitively. The main package must have package name main and declare
a function main that takes no arguments and returns no value.
func main() { … }
Program execution begins by initializing the main package and then
invoking the function main. When that function invocation returns, the
program exits. It does not wait for other (non-main) goroutines to
complete.

Related

Program executable does not run

If I run go build -o bin/test ./scripts/test.go I get an executable, but when I try to run it I get
Failed to execute process './bin/test'. Reason:
exec: Exec format error
The file './bin/test' is marked as an executable but could not be run by the operating system.
scripts/test.go
package scripts
import (
"fmt"
)
func main() {
fmt.Println("hello")
}
Should be package main:
package main
import "fmt"
func main() {
fmt.Println("hello")
}
https://tour.golang.org/welcome
The documentation for the go build command has the details about how this works.
Summary:
Building "main" packages will output an executable file
Building a non-main package will output an object (and discard it)
Building with -o will force the command to not discard the output, and save it to the specified file
So basically what you're doing here is building a non-main package, which outputs outputs an object file, not an executable. Normally this is discarded, but due to using the -o option you've forced it to output it to a file.
To get an actual executable, you just need to change the package name to main (as noted by Steven Penny)

function call difference between go build and go run

I'm new to Golang and I'm trying out a few examples as part of my learning. I have 2 Go source files - hello.go and consts.go in my example. consts.go contains some constants which are used by the functions defined in hello.go. When I build both the source files like so:
go build consts.go hello.go and run the output ./hello
the function arrayDemo() is not called at all.
However, when I just run the file hello.go using go run hello.go, the function arrayDemo() is called.
What is the difference in both the approaches that's causing the function not to be called when building?
Here's the code for hello.go:
package main
import (
"fmt"
"os"
"strconv"
"strings"
)
func main() {
fmt.Printf("Speed is %f\n", computeSpeed(54.3, 3.4))
fmt.Printf("%d\n", arrayDemo())
}
func arrayDemo() int32 {
fmt.Println("in arrayDemo")
return 5
}
Code for consts.go:
package main
// Speed speed of a vehicle
type Speed float32
func computeSpeed(dist float32, t float32) Speed {
return Speed(dist / t)
}
go run works because go run works based on file names, but go build works based on package names.
also
go help build says:
When compiling multiple packages or a single non-main package, build
compiles the packages but discards the resulting object, serving only
as a check that the packages can be built.
to my understanding this means you can not have multiple files in the main package and then get working executable by using go build

Struct from the same parent folder as main is not visible

I have a small go demo project in Gogland with the structure:
awsomeProject
->src
->awsomeProject
->configuration.go
->main.go
Configuration file has a simple structure just for demo:
configuration.go:
package main
type Config struct {
Data int
}
Main file just uses the Config struct:
main.go
package main
import "fmt"
func main(){
var cfg Config
cfg.Data = 1
fmt.Println("lalala")
}
The error that I have is:
/usr/local/go/bin/go run /Users/lapetre/Work/awsomeProject/src/awsomeProject/main.go
command-line-arguments
src/awsomeProject/main.go:6: undefined: Config
Process finished with exit code 2
Any idea why the Config is not seen in main?
Thanks
When you build reusable pieces of code, you will develop a package as a shared library. But when you develop executable programs, you will use the package “main” for making the package as an executable program. The package “main” tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program.
That's why you should use the following structure:
awsomeProject
->src
->awsomeProject
->configuration.go
->main.go
with main.go
package main
import "fmt"
func main(){
var cfg awsomeProject.Config
cfg.Data = 1
fmt.Println("lalala")
}
and configuration.go
package awsomeProject
type Config struct {
Data int
}
For more details:
https://golang.org/doc/code.html
https://thenewstack.io/understanding-golang-packages
How are you calling go run? If you're calling it like
go run main.go
then that's the problem.
Go run only runs the file(s) you tell it to. So you need to tell it to also run configuration.go, or if you have several go files to run you can use
go run *.go
as eXMoor suggested.
There are some limits/drawbacks to "go run *.go" however, so the better alternative is to use go build instead of go run.
go build
Will compile everything. Then, to run the executable:
./awesomeProject
To combine all of this into one command that will compile and run whatever app you're working on, you can use:
go build && ./${PWD##*/}
I have it aliased to
gorunapp
just to make it easier.
This may not actually be the answer to the problem you're having, but hopefully you'll find it useful information regardless.
Try to run your application with command:
go run *.go

How do Go plugin dependencies work?

Go 1.8 supports Go plugins.
I have created two plugins as follows.
As I understand, the plugin exposes only the functions and variables in the main package. i.e. plugin.Lookup() will fail for non-main variable/function.
But I wanted to test if a plugin can internally invoke a method from another plugin, similar to how a C++ library can invoke another library.
So I tested as follows:
plugin1 github.com/vimal/testplugin
$ cat myplugin.go
package main
import "C"
import "fmt"
import help "github.com/vimal/testplugin1/plug"
func init() {
fmt.Printf("main.init invoked\n")
}
// TestPlugin
func TestPlugin() string {
return help.Help()
}
plugin2 github.com/vimal/testplugin1
$ cat myplugin.go
package main
import "C"
func HelperFunc() string {
return "help"
}
$ cat plug/helper.go
package help
func Help() string {
return "help234"
}
Idea here is that plugin1 invokes an internal, non-main function of plugin2.
main program
Main program loads a number of plugins given as arguments, and invokes TestPlugin() from the last plugin.
test 1:
Build both plugins, and load both plugins, and invoke TestPlugin(), the output contains "help234", i.e. the inner function is invoked. This can be understood, since both plugins are loaded, one plugin can invoke another plugin's inner code.
test 2:
Load only plugin1, and invoke TestPlugin(), the output contains "help234", i.e. the inner function is invoked. The same output is observed as in test1. Perhaps this time the method is found from GOPATH.
test 3:
Rename the folder "github.com/vimal/testplugin1" to "github.com/vimal/junk1", delete the plugin2, and load only plugin1, and invoke TestPlugin(). the output still contains "help234", i.e. the inner function is invoked.
I am not able to understand how test3 produces the same output. Does plugin1 contain plugin2 code also? How can I understand the Go plugin dependency on other Go plugins?
Go version : go version go1.8rc3 linux/amd64
You're not doing exactly what you think you are.
Your plugin1 imports and uses a package, namely github.com/vimal/testplugin1/plug. This is not "equal" to plugin2!
What happens here is that when you build plugin1, all its dependencies are built into the plugin file, including the .../testplugin1/plug package. And when you load plugin1, all its dependencies are also loaded from the plugin file, including the plug package. After this, it's not surprising that it works no matter the loaded status of plugin2. These 2 plugins are independent from each another.
The -buildmode=plugin instructs the compiler that you want to build a plugin and not a standalone app, but it doesn't mean dependencies must not be included. They have to be, because the plugin cannot have any guarantee what Go app will load it, and what packages that Go app will have. Because a runnable app also only contains packages even from the standard library that the app itself references explicitly.
The only way to guarantee that the plugin will have everything it needs and so that it will work if it also contains all its dependencies, including those from the standard library. (This is the reason why building simple plugins generate relatively big files, similarly to building simple Go executables resulting in big files.)
Few things that don't need to be added to plugins include the Go runtime for example, because a running Go app that will load the plugin will already have a Go runtime running. (Note that you can only load a plugin from an app compiled with the same version of Go.) But beyond that, the plugin has to contain everything it needs.
Go is a statically linked language. Once a Go app or plugin is compiled, they do not rely nor check the value of GOPATH, it is only used by the Go tool during building them.
Deeper insight
It's possible that your main app and a plugin refers to the same package ("same" by import path). In such cases only one "instance" of the package will be used.
This can be tested if this commonly referred package has "state", e.g a global variable. Let's assume a common, shared package called mymath:
package mymath
var S string
func SetS(s string) {
S = s
}
And a plugin called pg that uses it:
package main
import (
"C"
"mymath"
"fmt"
)
func Start() {
fmt.Println("pg:mymath.S", mymath.S)
mymath.SetS("pghi")
fmt.Println("pg:mymath.S", mymath.S)
}
And the main app that uses mymath and loads pg (which uses it):
package main
import (
"plugin"
"mymath"
"fmt"
)
func main() {
fmt.Println("mymath.S", mymath.S)
mymath.SetS("hi")
fmt.Println("mymath.S", mymath.S)
p, err := plugin.Open("../pg/pg.so")
if err != nil {
panic(err)
}
start, err := p.Lookup("Start")
if err != nil {
panic(err)
}
start.(func())()
fmt.Println("mymath.S", mymath.S)
}
Building the plugin:
cd pg
go build -buildmode=plugin
Running the main app, the output is:
mymath.S
mymath.S hi
pg:mymath.S hi
pg:mymath.S pghi
mymath.S pghi
Analysis: first the main app plays with mymath.S, sets it to "hi" eventually. Then comes the plugin, which prints it (we see the value set by the main app "hi"), then changes it to "pghi". Then comes again the main app and prints mymath.S, and again, sees the last value set by the plugin: "pghi".
So there is only one "instance" of mymath. Now if you go ahead and change mymath, e.g. rename myMath.SetS() to mymath.SetS2(), and you update the call in the main app (to mymath.SetS2("hi")), and without rebuilding the plugin, just running the main app, you get the following output:
mymath.S
mymath.S hi
panic: plugin.Open: plugin was built with a different version of package mymath
goroutine 1 [running]:
main.main()
<GOPATH>/src/play/play.go:16 +0x4b5
exit status 2
As you can see, when building the main app and the plugin, the package version (which is most likely a hash) is recorded, which must match if their import paths match in the main app and in the plugin.
(Note that you will also get the above error if you don't change the exported identifiers (and signatures) of the used mymath package, only the implementation; e.g. func SetS(s string) { S = s + "+" }.)

How to use multiple .go files in the same application

Good Morning All,
I am new to Golang. I want to move some of my functions out into separate files so that I will not have like a 10,000 line .go file at the end. lol. I created two files both have the same package called main. Do I need to change package name to be app specific? Anyway how do I get these two files to talk?
Example:
MainFile.go:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello World!")
Test()
}
NewFile.go:
package main
import (
"fmt"
)
func Test() {
fmt.Println("Hello World Again!")
}
The test method is in the second file but cannot be reached by the first. I am sure this is some rudimentary thing I am missing.
Thanks
Update:
I tried specifying this on the command line: go build MainFile.go NewSourceFile.go. It comes back with no errors but never builds the binary. How do I get it to output the binary now?
If you run go run MainFile.go, Test() won't be found because its not in that file. You have to build the package then run the package:
Inside the folder where the 2 files are, run go build and you will get a binary in that folder. Then just run the binary: ./MyPackage

Resources