Create and Run Go Project
Create a Go Project
To create a new Go project, use the go mod init <project-name> command.
This style of project name is recommended for Go projects.
This will create a new directory named my-project with the following structure:
Run the Project
- If you use
go run main.go, it will only run themain.gofile. If you're importing other files, you need to use thego run .command. Else, usego run main.go helper.go ...to run multiple files.
Build the Project
Install external packages
- This will install the package in the
go.modfile andgo.sumfile.
Install external go executables binaries
go.mod vs go.sum
| Aspect | go.mod | go.sum |
|---|---|---|
| Purpose | Tracks direct dependencies and Go version. | Verifies and locks exact versions and hashes. |
| Editable | Yes (manually or by Go tools). | No (automatically maintained by Go tools). |
| Contents | Module names and versions. | Module names, versions, and their checksums. |
| Scope | Focuses on top-level dependencies. | Includes transitive dependencies. |
Best Practices
- Commit both files to version control to ensure a consistent build environment.
- Regularly run
go mod tidyto clean up unused dependencies and sync go.sum. - Use go.sum as a security featureβverify that dependencies havenβt been altered.
go mod tidy command
- Removes Unused Dependencies:
- Adds Missing Dependencies:
- Updates go.sum
go mod tidyis a Go command used to clean up and optimize your project's dependency files (go.mod and go.sum).- It ensures that your module's dependency list is accurate and minimal, reflecting only the libraries and versions you truly need.
go install
To install a local binary package, use the go install command.
It installs the executable binary in the $GOPATH/bin directory. Mostly ~/go/bin directory.