Learing by analogy - Golang package system based on NodeJS
Imagine you’re a experienced NodeJS developer and are starting to learn golang. Once you’ve learned the basic language concepts, soon or later you’ll need to use some package and how it works.
You’re an expert about the NodeJS package ecosystem and terms like “package.json”, “node_modules” and “npm install” are very familiar to you. But in the context of golang package management, is there any parallel that we can make to the NodeJS package management to understand it better? In this small article we’re going to learn the golang package management by nodeJS analogies. (This post used some chatGPT help to be created :))
The `go.mod` file
The `go.mod` file is the equivalent of the `package.json` file in Node.js. It defines the module that your code belongs to, as well as its dependencies. The `go.mod` file also specifies the version of the Go language that your code is compatible with. You can create a new Go module by running the `go mod init` command in the root directory of your project. For example:
go mod init myproject
This will create a new `go.mod` file in your project’s root directory. The `go.mod` file will initially be empty, but you can add dependencies to it as you need them.
Adding Dependencies
To add a dependency to your project, you can use the `go install` command. For example, if you wanted to add the `gorilla/mux` package to your project, you would run:
go install github.com/gorilla/mux
This will download the `gorilla/mux` package and add it to your `go.mod` file as a dependency. The package and all its dependencies will be downloaded and stored in a cache folder called `go/pkg/mod`.
Directory Structure
In terms of directory structure, Go uses a flat directory structure for packages, unlike the nested `node_modules` structure used in Node.js. When you import a package in Go, the compiler looks for the package in a global cache directory called `go/pkg`, which is located in your Go installation directory. So, in summary, the equivalent of a `package.json` file in Go is a `go.mod` file, and the equivalent of the `node_modules` folder is a global cache directory called `go/pkg`.