Home >Backend Development >Golang >How to Properly Structure Go Modules and Projects in Go 1.11 and Beyond?
How to Structure Golang Modules and Project Structure in the New way
In the updated module system introduced in Go 1.11, the approach to referencing modules from different directories has evolved. Let's explore how to achieve this in the new way.
Old Way
Previously, modules needed to be placed in the GOPATH for use. Typically, a folder was created within the GOPATH for each project. Everything within the "src" directory could be imported and exported into software.
For example, consider the following project structure:
github.ibm.com/ └── Alessio-Savi └── GoLog-Viewer ├── conf ├── database ├── datastructure ├── GinProva.go ├── README.md ├── request └── resources
To import the datastructures.go file, the following statement could be used:
import( "github.ibm.com/Alessio-Savi/GoLog-Viewer/datastructure" )
New Way
With the introduction of go modules, the use of GOPATH is no longer necessary. Instead, the 'go mod init' command can be used to initialize a new module. This generates two files: go.mod and go.sum.
The go.mod file lists the required libraries and external Go code needed for the module, while go.sum contains hashes of those libraries.
For example, consider the GoGPUtils library:
mkdir GoGPUtils cd $_ go mod init github.com/alessiosavi/GoGPUtils
The go.mod file would look something like this:
module github.com/alessiosavi/GoGPUtils go 1.13 require ( github.com/alessiosavi/ahocorasick v0.0.3 golang.org/x/tools v0.0.0-20191031220737-6d8f1af9ccc0 // indirect )
To import the ahocorasick library within the module, the following statement can be used:
import ( ahocorasick "github.com/alessiosavi/ahocorasick" )
In your example scenario, to access module2 from module1, you would need to include the path to module2 in the go.mod file of module1. For example:
require ( github.com/your-username/module2 v0.0.1 )
The above is the detailed content of How to Properly Structure Go Modules and Projects in Go 1.11 and Beyond?. For more information, please follow other related articles on the PHP Chinese website!