Building and running programs
Now that you have a module and a source tree with some Go files, you can build or run your program.
How to do it...
- Use
go build
to build the current package - Use
go build ./path/to/package
to build the package in the given directory - Use
go build <moduleName>
to build a module - Use
go run
to run the currentmain
package - Use
go run ./path/to/main/package
to build and run themain
package in the given directory - Use
go run <moduleName/mainpkg>
to build and run the module’s main under the given directory
Let’s write the main
function that starts an HTTP server. The following snippet is cmd/webform/main.go
:
package main import ( "net/http" ) func main() { server := http.Server{ Addr: ":8181", Handler: http.FileServer(http.Dir("web/static")), } server.ListenAndServe() }
Currently, main
only imports the standard library’s net/http
package. It starts a server that serves the files under the web/static
directory. Note that for this to work, you have to run the program from the module root:
$ go run ./cmd/webform
Always run the main
package; avoid go run main.go
. This will run main.go
, excluding any other files in the main package. It will fail if you have other .go
files that contain helper functions in the main
package.
If you run this program from another directory, it will fail to find the web/static
directory; because it is a relative path, it is resolved relative to the current directory.
When you run a program via go run
, the program executable is placed in a temporary directory. To build the executable, use the following:
$ go build ./cmd/webform
This will create a binary in the current directory. The name of the binary will be determined by the last segment of the main package – in this case, webform
. To build a binary with a different name, use the following:
$ go build -o wform ./cmd/webform
This will build a binary called wform
.