-
Book Overview & Buying
-
Table Of Contents
Go Recipes for Developers
By :
Now that you have a module and a source tree with some Go files, you can build or run your program.
go build to build the current packagego build ./path/to/package to build the package in the given directorygo build <moduleName> to build a modulego run to run the current main packagego run ./path/to/main/package to build and run the main package in the given directorygo run <moduleName/mainpkg> to build and run the module’s main under the given directoryLet’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.