Go modules

Go modules were introduced in Go 1.11. They afford the ability to keep track of versioned dependencies within a Go code base. They are a collection of Go packages that are stored as a cohesive unit in a go.mod file within a project directory.

We will perform the following steps to initialize a new module:

  1. We first execute go mod init repository:
go mod init github.com/bobstrecansky/HighPerformanceWithGo
go: creating new go.mod: module github.com/bobstrecansky/HighPerformanceWithGo
  1. After you've initialized this new module, you can build your Go package and execute it as you normally would. You'll have any imported modules from within your project saved in a go.mod file within your project's directory.

As an example, if we want to be able to create a simple web server using the Gin framework [https://github.com/gin-gonic/gin], we would create a directory for this in our project structure as follows: /home/bob/git/HighPerformanceWithGo/6-composing-readable-go-code/goModulesExample.

  1. We next create a simple web server that returns a response with  bar to a /foo request:
package main
import "github.com/gin-gonic/gin"
func main() {
server := gin.Default()
server.GET("/foo", func(c *gin.Context) {
c.JSON(200, gin.H{
"response": "bar",
})
})
server.Run()
}
  1. After this, we can create a new Go module in our newly created directory:

  1. Next, we can execute our Go program; the proper dependencies will be pulled in as necessary:

We can now see that we have our dependencies for our simple web server stored in the go.sum file within our directory (I've used the head command to truncate the list to the top 10 entries):

Go modules help keep vendored items within a Go repository clean and consistent. We can also use a vendored repository if we want to keep all of our dependencies local to our project.

Opinions on vendoring dependencies within your repository often vary greatly. Some like to use a vendored repository because it decreases build time and limits the risk of not being able to pull packages from an external repository. Others feel that vendoring can be a hindrance to package updates and security patches. Whether you choose to use a vendored directory in your program is up to you, but the fact that Go modules include this functionality in the language is convenient. The following output illustrates this:

Being able to vendor directories with the built-in compilation tools makes it easy to set up and configure. 

In the next section, we will discuss naming things in Go.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.135.80