Go modules provide a way to manage dependencies and versioning for Go projects. They replace the old GOPATH method and offer a more flexible and robust system.

  1. Initializing a Go Module Let’s create a new project and initialize a Go module.

    1. Create a new directory for your project:

        mkdir myproject
      cd myproject
        
    2. Initialize a new module:

        go mod init example.com/myproject
        

      This command creates a go.mod file in your project directory, which looks like this:

        module example.com/myproject
      
      go 1.16
        
  2. Adding Dependencies To add dependencies to your project, you can import them in your code and run go mod tidy to update the go.mod and go.sum files.

    1. Create a simple Go program that uses an external dependency. For this example, we’ll use the logrus logging package.

      Create a main.go file with the following content:

        // main.go
      package main
      
      import (
         "github.com/sirupsen/logrus"
      )
      
      func main() {
         logrus.Info("Hello, Go Modules!")
      }
        
    2. Run the following command to download the dependency and update your module files:

        go mod tidy
        

      This will update the go.mod file to include the logrus dependency and create a go.sum file to record the precise versions of your dependencies.

      The go.mod file now looks like this:

        module example.com/myproject
      
      go 1.16
      
      require github.com/sirupsen/logrus v1.8.1
        

      The go.sum file contains checksums for the dependencies to ensure they haven’t been tampered with.

  3. Managing Dependencies You can update or change the version of a dependency using the go get command. For example, to update the logrus dependency to a specific version:

      go get github.com/sirupsen/[email protected]
      

    This updates the require line in go.mod and adjusts the go.sum file accordingly.

  4. Using the vendor Directory If you need to include all dependencies in a vendor directory, you can use the go mod vendor command:

      go mod vendor
      

    his copies all the dependencies to a vendor directory in your project, which can be useful for ensuring consistent builds and for environments where internet access is restricted.

  5. Running and Building the Project Run your project using the go run command:

      go run main.go
      

    This should output:

      INFO[0000] Hello, Go Modules!
      

    To build the project, use the go build command:

      go build
      

    This will create an executable in your project directory.