In this article, we will go through a handy script we working with Go modules. Since the introduction of the Go module, a command must run each time you want to update or import a new package.
In this example, we will be creating a script file that contains all the necessary command(s) to update or import packages without the need to write commands in your terminal every time. Furthermore, this script file can later be modified based on your personal preferences.
From version 1.11 onwards Go support modules which is a collection of Go packages stored in a file called go.mod. The advantage of Go module is its independency since the file contains the descriptions of all packages (version specific) belonging to the project. This is handy in case there is an older project that still required an older version of a package.
In this example, we will be using the Go IDE GoLand which is a complete package with it comes to Go development.
Create a new project
We will start by creating a new project and the
go.mod file is added by default for you.
Next, create the main application file
After creating your main application file, create the shell script file. In this example, we will call it
update_module.sh, but you can name it whatever you want.
Type the following code:
#!/bin/bash echo "Updating module file..." go mod tidy echo "Module file updated!"
Install a plugin called shell_script. By going the through the setting:
- macOS: GoLand -> Preference
- Windows: File -> Settings
In my case I already have it installed!
This plugin enables you to run the script with a click of a button.
The next step is to import a Go package into the project. For this project, we will be using the QR code package from our QR code article, thus:
You can copy and paste the code from the code article into your main application file. In our case, we just took a portion of the code for this project and it looks like the following:
As you can see, you are getting an error and it is because the package is not yet imported. To import the packages, just run the script file by clicking on the run button.
And your terminal should display the following:
If everything went well all the errors should disappear.
With this script file, you can continue importing and updating packages by just clicking the run button and that’s it. No more manually entering the command in the terminal etc.