-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Go Recipes for Developers
By :
When you start working on a new project, the first thing to do is to create a module for it. A module is how Go manages dependencies.
go mod init <moduleName> to create the new module. The go.mod file marks the root directory of a module. Any package under this directory will be a part of this module unless that directory also has a go.mod file. Although such nested modules are supported by the build system, there is not much to be gained from them.moduleName/packagePath. When moduleName is the same as the location of the module on the internet, there are no ambiguities about what you are referring to.go.mod file. All references to other packages within a module will be looked up in the directory tree under the module root.$HOME/projects (or \user\myUser\projects in Windows). You may choose to use a directory structure that looks like the module name, such as $HOME/github.com/mycompany/mymodule (or \user\myUser\github.com\mycompany\mymodule in Windows). Depending on your operating system, you may find a more suitable location.Warning
Do not work under the src/ directory of your Go installation. That is the source code for the Go standard library.
Tip
You should not have an environment variable, GOPATH; if you have to keep it, do not work under it. This variable was used by an older mode of operation (Go version <1.13) that is now deprecated in favor of the Go module system.
Throughout this chapter, we will be using a simple program that displays a form in a web browser and stores the entered information in a database.
After creating the module directory, use go mod init. The following commands will create a webform directory under projects and initialize a Go module there:
$ cd projects $ mkdir webform $ go mod init github.com/examplecompany/webform
This will create a go.mod file in this directory that looks like this:
module github.com/PacktPublishing/Go-Recipes-for-Developers/chapter1/webform go 1.21.0
Use a name that describes where your module can be found. Always use a URL structure such as the <host>.<domain>/location/to/module format (e.g., github.com/bserdar/jsonom). In particular, the first component of the module name should have a dot (.) (the Go build system checks this).
So, even though you can name the module something such as webform or mywork/webform, do not do so. However, you can use something such as workspace.local/webform. When in doubt, use the code repository name.