How to Install and Configure Go on Ubuntu: A Step-by-step Guide

How to Install and Configure Go on Ubuntu: A Step-by-step Guide
Anees Asghar
Technical writer
Go
18.10.2024
Reading time: 6 min

Go, also known as Golang, is a programming language created by Google. It simplifies coding and provides great performance, which makes it popular among developers. Its user-friendly syntax and built-in concurrency support allow developers to efficiently create scalable applications. Moreover, Go is a cross-platform programming language and is available for all major operating systems, including Linux, Windows, etc. On our app platform you can find various Go frameworks, such as Beego and Gin.

In this article, we’ll discuss what Golang is and how to install and use it on Ubuntu.

What is Golang?

Golang is a simple yet powerful programming language that enables developers to build basic to advanced applications. Go was developed to manage large-scale projects, with a focus on concurrency and clean code. Its scalability and cross-platform compatibility have made it a popular choice among developers.

Go is widely used in systems programming, networking, and microservices. Key benefits of Golang include fast compilation, simple syntax, automatic memory management, and tools like go fmt and go test.

Prerequisites for Installing Go on Ubuntu

To install the Go language on Ubuntu, the below-listed requirements must be fulfilled:

  • Ubuntu must be pre-installed.
  • A user with root or sudo privileges.

If a user fulfills the prerequisites, he can proceed with the installation of Go on Ubuntu.

Method 1: Installing Golang on Ubuntu via the Default Package Manager

Apt is the default package manager of Ubuntu. Installing Golang through the default package is the most convenient way. However, it’s important to note that the version installed via Ubuntu's default package manager may not always be the latest.

Let’s go through the below-listed steps to install Go on Ubuntu through apt:

Updating and Upgrading System Repositories

Before installing Golang on Ubuntu, it is recommended to update and upgrade the system repositories to ensure we have the latest package information:

sudo apt update && sudo apt upgrade -y

Image1

Installing Go Using apt

Now run the command below to install Go on Ubuntu using the default package manager:

sudo apt install golang-go -y

Image3

The installation process for Golang on Ubuntu may take a while to complete. 

Verify Go Language Installation

Finally, confirm the Golang installation on Ubuntu by checking its version:

go version

The output indicates that the go version go1.22.2 has been installed successfully:

Image2

Uninstall Go from Ubuntu

If Golang is no longer needed, uninstall it from Ubuntu by executing the following command:

sudo apt remove golang-go -y

Image5

It's recommended to remove unnecessary dependent packages, as they can take up extra space. To do this, simply execute the below-given command:

sudo apt autoremove

Image4

Method 2: Installing Golang Using wget

To install the Go programming language on Ubuntu from the official source, users can use the wget command. This command downloads the latest Golang binary package from the official website. 

Let’s go through the step-by-step process below to download and install Golang on Ubuntu using the wget command.

Download and Install Go Language

First, open a browser and navigate to the Go language’s official All Releases page. Scroll down to select an appropriate binary package under the stable version. Copy the link address of the selected binary package:

Image7

Now specify the copied link address with the wget command, as shown below:

wget https://go.dev/dl/go1.23.2.linux-amd64.tar.gz -O golang.tar.gz

Here, the -O option is used to specify an output file name. For instance, the above command downloads the Golang binary package and saves it as golang.tar.gz:

Image6

After this, use the tar command to extract the downloaded package:

sudo tar -xzvf golang.tar.gz -C /usr/local

Image9

Set Up the Go Environment

Configuring the PATH variable for Golang allows access to Go commands and tools from any directory on the system. For this purpose, the Go binary paths need to be added to the PATH environment variable:

echo export PATH=$HOME/golang/bin:/usr/local/go/bin:$PATH >> ~/.profile

Image8

Next, execute the following command to apply the changes made to the profile file:

source ~/.profile

Image12

Verify Go Installation

Once the Go environment is configured, execute the command below to check if Go has been successfully installed:

go version

Image10

Configure the $GOPATH and $GOROOT (Optional)

In Golang, the default workspace directory is ~/go, and the environment variable $GOPATH refers to this location. However, users can customize this workspace by setting the $GOPATH environment variable in their ~/.profile, ~/.bashrc, or ~/.zshrc files:

export GOPATH=$HOME/golangExamples

This command will set the workspace directory to ~/golangExamples. Moreover, users can also set $GOROOT to override the default Go installation path. However, this is usually not necessary:

export GOROOT=/usr/local/go

Finally, execute the command below to apply the changes:

source ~/.profile

Users can customize the $GOPATH and $GOROOT environment variables, however, it is not recommended to change them unless you have a specific reason.

Remove Go From Ubuntu

If Golang is downloaded using the wget command and now needs to be removed, simply run the command below:

sudo rm -rf /usr/local/go

This command will permanently remove the Go language from Ubuntu. 

How to Use Go Programming Language on Ubuntu?

Once the Go programming language is installed on Ubuntu, we can use it to fulfill our programming needs, such as creating applications, and web services, handling concurrent tasks, etc. 

You can use any text editor, like nano, to create a new file and save it with a .go extension:

nano exampleCode.go

After creating a go file, paste the following code into it to print a "Welcome to hostman.com" message on the terminal:

package main

import "fmt"

func main() {
    fmt.Println("Welcome to hostman.com")
}

Save the code, close the nano editor, and then run the command below in the terminal to execute the Go program:

go run exampleCode.go

The output shows that the "Welcome to hostman.com" message is successfully displayed in the Ubuntu terminal, which confirms that the Golang program has been executed correctly:

Image11

That’s all about installing, configuring, and using the Go programming language on Ubuntu.

Conclusion

Golang is a cross-platform programming language best known for its easy-to-use syntax, concurrency support, and scalability. Key benefits of Golang include fast compilation, simple syntax, and built-in tools like go fmt and go test, etc. These features make Golang a perfect choice for building efficient applications. In this article, we explored two methods to install Golang on Ubuntu. The first method uses the default package manager (apt). The second method involves downloading via wget. Choose any of the discussed methods to install the Go language and start using it to develop scalable applications on Ubuntu.

Go
18.10.2024
Reading time: 6 min

Similar

Go

How to Create and Deploy a Gin App on Hostman App Platform

Gin is a highly efficient HTTP web framework written in the Go programming language, providing developers with powerful tools for building web applications, RESTful APIs, and microservices. It stands out among other frameworks due to its high request processing speed, flexible configuration, and ease of use. One of Gin’s key advantages is its performance. Gin uses a minimalist approach to handling HTTP requests, making it one of the fastest frameworks on the market. It is built on the net/http module from Golang’s standard library, ensuring excellent integration with Go’s ecosystem and enabling the use of Go’s concurrency features to handle a large number of simultaneous requests. Another important advantage of Gin is its simplicity. The syntax and structure of Gin are intuitive, reducing the learning curve for developers and speeding up the development process. Its built-in routing system makes it easy to define and handle routes, while its powerful middleware system allows flexible request handling. Gin’s flexibility is also worth mentioning. It allows you to extend functionality  through plugins and middleware, enabling adaptation to specific project requirements. Built-in support for JSON and other data formats simplifies the creation of RESTful APIs, and tools for handling requests and responses make data management straightforward. In addition, Gin has an active community and solid documentation, making it an excellent choice for developers looking for a reliable and well-supported framework. There are plenty of resources, including code examples, guides, and libraries, that make the learning and development process easier. Creating the Application Functionality Overview Our application will support basic CRUD operations (Create, Read, Update, Delete) for notes through a RESTful API. During development, we will discuss key aspects of integrating Gin with the GORM ORM library and demonstrate how to ensure the security and performance of our web application. The main features of our application include: Creating a New Note The user can add a new note by sending a POST request with the note’s title and content. The application will save the new note in the database and return its unique identifier. Retrieving All Notes The user can request a list of all notes by sending a GET request. The application will return all notes from the database in JSON format. Retrieving a Note by ID The user can retrieve a specific note by its ID by sending a GET request with the specified ID. The application will find the note in the database and return it in JSON format. Updating an Existing Note The user can update an existing note by sending a PUT request with a new title and content. The application will update the note’s data in the database and return the updated note. Deleting a Note The user can delete a note by its ID by sending a DELETE request with the specified ID. The application will remove the note from the database and return a status indicating the successful completion of the operation. Project Setup It is assumed that you have Go version 1.22 installed (you can install it using one of these guides: Windows, Ubuntu, MacOS). If you use an earlier version, errors may occur during the project setup and launch process. Additionally, you should have a basic understanding of Git and an account on one of the Git repository hosting services (GitHub, GitLab, Bitbucket, Gitea, etc.). Step 1: Create a Project Directory Run the following command to create the project directory: mkdir GinApp Navigate into the newly created directory: cd GinApp Step 2: Initialize a New Go Module Run the following command to initialize a new Golang module: go mod init gin-notes-api Step 3: Install Required Packages We will install the necessary packages for the project: Gin, GORM, and SQLite (for database interaction) using the following commands: go get -u github.com/gin-gonic/gin go get -u gorm.io/gorm go get -u gorm.io/driver/sqlite Step 4: Create the Project Structure The project structure should look like this: GinApp/ ├── go.mod ├── main.go ├── models/ │ └── note.go ├── handlers/ │ └── note_handlers.go ├── storage/ │ ├── storage.go │ └── database.go You can create this structure using your IDE’s file explorer or by running the following command in the terminal: mkdir -p models handlers storage && touch go.mod main.go models/note.go handlers/note_handlers.go storage/storage.go storage/database.go Application Structure models/note.go Defines the data structure for notes. The Note model describes the fields of a note and is used to interact with the database through the GORM ORM library. package models // Definition of the Note structure type Note struct { ID int `json:"id" gorm:"primaryKey;autoIncrement"` // Unique identifier, auto-incremented Title string `json:"title"` // Note title Content string `json:"content"` // Note content } storage/database.go This file contains functions for initializing the database and retrieving the database instance. GORM is used to work with the SQLite database. package storage import ( "gorm.io/driver/sqlite" // Driver for SQLite "gorm.io/gorm" // GORM ORM library "gin-notes-api/models" // Importing the package with data models ) // Declare a global variable to store the database instance var db *gorm.DB // Function to initialize the database func InitDatabase() error { var err error db, err = gorm.Open(sqlite.Open("notes.db"), &gorm.Config{}) // Connect to SQLite using GORM if err != nil { return err // Return an error if the connection fails } return db.AutoMigrate(&models.Note{}) // Automatically create the Note table if it doesn’t exist } // Function to retrieve the database instance func GetDB() *gorm.DB { return db // Return the global db variable containing the database connection } storage/storage.go This file provides CRUD (Create, Read, Update, Delete) operations for the Note model using GORM to interact with the SQLite database. package storage import ( "gin-notes-api/models" // Importing the package with data models ) // Function to retrieve all notes from the database func GetAllNotes() []models.Note { var notes []models.Note db.Find(¬es) // Use GORM to execute a SELECT query and fill the notes slice return notes // Return all retrieved notes } // Function to retrieve a note by ID func GetNoteByID(id int) *models.Note { var note models.Note if result := db.First(¬e, id); result.Error != nil { return nil // Return nil if the note with the specified ID is not found } return ¬e // Return the found note } // Function to create a new note func CreateNote(title, content string) models.Note { note := models.Note{ Title: title, Content: content, } db.Create(¬e) // Use GORM to execute an INSERT query and save the new note return note // Return the created note } // Function to update an existing note by ID func UpdateNote(id int, title, content string) *models.Note { var note models.Note if result := db.First(¬e, id); result.Error != nil { return nil // Return nil if the note with the specified ID is not found } note.Title = title note.Content = content db.Save(¬e) // Use GORM to execute an UPDATE query and save the updated note return ¬e // Return the updated note } // Function to delete a note by ID func DeleteNoteByID(id int) bool { if result := db.Delete(&models.Note{}, id); result.Error != nil { return false // Return false if deletion fails } return true // Return true if the note is successfully deleted } handlers/note_handlers.go This file contains handler functions for processing HTTP requests. These functions are triggered in response to different routes and perform actions such as creating, retrieving, updating, and deleting notes. package handlers import ( "net/http" // HTTP package "strconv" // For converting strings to other data types "github.com/gin-gonic/gin" // Gin web framework "gin-notes-api/storage" // Import the storage module for database operations ) // Handler for retrieving all notes func GetNotes(c *gin.Context) { notes := storage.GetAllNotes() // Fetch all notes from storage c.JSON(http.StatusOK, notes) // Return notes in JSON format with a 200 OK status } // Handler for retrieving a note by ID func GetNoteByID(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) // Convert the ID parameter from string to integer if err != nil { c.JSON(http.StatusBadRequest, gin.H{ // Return 400 Bad Request if the ID is invalid "error": "Invalid note ID", }) return } note := storage.GetNoteByID(id) // Fetch the note by ID from storage if note == nil { c.JSON(http.StatusNotFound, gin.H{ // Return 404 Not Found if the note is not found "error": "Note not found", }) return } c.JSON(http.StatusOK, note) // Return the found note in JSON format with a 200 OK status } // Handler for creating a new note func CreateNote(c *gin.Context) { var input struct { Title string `json:"title" binding:"required"` Content string `json:"content" binding:"required"` } if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{ // Return 400 Bad Request if the input data is invalid "error": err.Error(), }) return } note := storage.CreateNote(input.Title, input.Content) // Create a new note in storage c.JSON(http.StatusCreated, note) // Return the created note in JSON format with a 201 Created status } // Handler for updating an existing note by ID func UpdateNoteByID(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) // Convert the ID parameter from string to integer if err != nil { c.JSON(http.StatusBadRequest, gin.H{ // Return 400 Bad Request if the ID is invalid "error": "Invalid note ID", }) return } var input struct { Title string `json:"title" binding:"required"` Content string `json:"content" binding:"required"` } if err := c.ShouldBindJSON(&input); err != nil { c.JSON(http.StatusBadRequest, gin.H{ // Return 400 Bad Request if the input data is invalid "error": err.Error(), }) return } note := storage.UpdateNote(id, input.Title, input.Content) // Update the note in storage if note == nil { c.JSON(http.StatusNotFound, gin.H{ // Return 404 Not Found if the note is not found "error": "Note not found", }) return } c.JSON(http.StatusOK, note) // Return the updated note in JSON format with a 200 OK status } // Handler for deleting a note by ID func DeleteNoteByID(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) // Convert the ID parameter from string to integer if err != nil { c.JSON(http.StatusBadRequest, gin.H{ // Return 400 Bad Request if the ID is invalid "error": "Invalid note ID", }) return } if success := storage.DeleteNoteByID(id); !success { c.JSON(http.StatusNotFound, gin.H{ // Return 404 Not Found if the note is not found "error": "Note not found", }) return } c.Status(http.StatusNoContent) // Return 204 No Content on successful deletion } main.go This file serves as the main entry point of the application. It initializes the database and sets up routes for handling HTTP requests using the Gin web framework. package main import ( "log" // Package for logging "github.com/gin-gonic/gin" // Gin web framework "gin-notes-api/handlers" // Importing the module with request handlers "gin-notes-api/storage" // Importing the module for database operations ) func main() { // Initialize the database if err := storage.InitDatabase(); err != nil { log.Fatalf("Failed to initialize database: %v", err) // Log the error and terminate the program if database initialization fails } // Create a new Gin router with default settings router := gin.Default() // Define routes and bind them to their respective handlers router.GET("/notes", handlers.GetNotes) // Route for retrieving all notes router.GET("/notes/:id", handlers.GetNoteByID) // Route for retrieving a note by ID router.POST("/notes", handlers.CreateNote) // Route for creating a new note router.PUT("/notes/:id", handlers.UpdateNoteByID) // Route for updating a note by ID router.DELETE("/notes/:id", handlers.DeleteNoteByID) // Route for deleting a note by ID // Start the web server on port 8080 router.Run(":8080") } Now we can run the application locally and test its functionality. To start the application, use the following command: go run main.go Examples of curl Requests for Testing Functionality Create a New Note This request creates a new note with a specified title and content. curl -X POST http://localhost:8080/notes \ -H "Content-Type: application/json" \ -d '{"title":"Title","content":"Note body"}' Get All Notes This request retrieves a list of all notes stored in the database. curl -X GET http://localhost:8080/notes Get a Note by ID This request fetches a specific note by its unique ID. curl -X GET http://localhost:8080/notes/1 Update a Note by ID This request updates an existing note by its ID, providing a new title and content. curl -X PUT http://localhost:8080/notes/1 \ -H "Content-Type: application/json" \ -d '{"title":"Updated Title","content":"Updated note body"}' Delete a Note by ID This request deletes a note with a specific ID. curl -X DELETE http://localhost:8080/notes/1 Deploying the Gin Application on Hostman App Platform Creating and Uploading the Repository To deploy the application using Hostman App Platform, first ensure your project is hosted in a Git repository. This example uses GitHub. Initialize a Git repository locally in your project directory: git init -b main git add . git commit -m 'First commit' Push the repository to a remote server using the commands provided when creating a new GitHub repository: git remote add origin [email protected]:your_user/your_repository.git git push -u origin main Setting Up Hostman App Platform Go to the App Platform section in Hostman and click Create app. Under the Type section, choose the Backend tab and select the Gin framework. Connect your GitHub account by granting access to the repositories, or manually select the necessary repository. After connecting your GitHub account, select the repository containing your application in the Repository section. Choose a region where your application will be hosted. In the Configuration section, select the minimum settings; they are sufficient for this project. You can modify them later if needed. Leave the default values in the App settings section. For more complex projects, you may specify environment variables and custom build commands. Specify a name for your application and click Start deploy. Deployment Process The deployment process can take up to 10 minutes. Once it’s completed, you will see the message “Deployment successfully completed” in the deployment logs. Navigate to the Settings tab on the application page to view the domain assigned to your app.In the same section, you can modify the server configuration, edit deployment settings, and update the domain binding. If you connect a custom domain, a Let’s Encrypt SSL certificate will be automatically issued and renewed 7 days before expiration. Testing the Application To verify that the application is working correctly, execute a curl request, replacing localhost with the assigned domain: curl -X GET https://your_domain/notes Conclusion In this tutorial, we have developed a basic web application for managing notes using the Gin framework and GORM library. The created RESTful API supports basic CRUD operations, making the application simple and user-friendly. Gin proved to be an efficient and easy-to-learn tool. Its routing system and support for concurrent requests made development smoother. GORM facilitated database interaction by automating many tasks. The application was successfully deployed on the Hostman App Platform, providing a fast and reliable deployment process.  In the future, we can enhance the application by adding new features such as user authentication and advanced note search capabilities. This project demonstrated how modern development tools like Gin and GORM simplify web application creation.
16 January 2025 · 14 min to read
Go

For Loops in the Go Programming Language

A loop is a block of code that runs until a specified condition is met or a required number of repetitions is completed. Loops are convenient for solving tasks where a program needs to repeat the same actions multiple times. For example, imagine you have a list of directors. You need to extract each director's last name and display it on the screen. Instead of manually accessing each element of the list, it's easier to use a loop. A loop will iterate through the list and display each last name on the screen. Loops in Go In Go, there are only for loops. There are no while or do while loops like in some other languages. Similar concepts are implemented using the same for loop. This design choice makes the code more readable. Developers don't have to decide on a looping strategy — if you need to repeat actions, there's for, which can be used in various ways. Let's explore how to create loops in Golang to solve specific tasks. ForClause The structure of a ForClause is simple. It consists of a condition and a body. The code inside the body executes if the condition is evaluated as true. for i := 0; i < 6; i++ { fmt.Println(i) } Here: i := 0 is the initializer. It sets the starting value of the loop. i < 6 is the condition. If it is evaluated as true, the code inside the loop is executed. fmt.Println(i) sequentially prints numbers from 0 to 5. i++ is the post-operation that increments i by 1 after each iteration. The code starts with i = 0. Since 0 < 6, the condition is true, and 0 is printed. Then, i++ increments i by 1, making i = 1. The loop continues as long as i < 6. When i becomes 6, the condition i < 6 is false, and the loop stops. The number 6 is not printed. Output: 0 1 2 3 4 5 You don't have to start at zero or stop at a fixed value. The for loop in Go allows you to adjust the logic as needed. for i := 100; i < 150; i = i + 10 { fmt.Println(i) } Output: 100 110 120 130 140 If you modify the condition slightly, you can include the number 150: for i := 100; i <= 150; i = i + 10 { fmt.Println(i) } Output: 100 110 120 130 140 150 You can also iterate in reverse, from the end to the beginning, by modifying the condition and the post-operation. for i := 50; i > 0; i -= 10 { fmt.Println(i) } Here, the loop starts with i = 50. On each iteration, it checks if i > 0. If the condition is true, it subtracts 10 from the current value of i. Output: 50 40 30 20 10 Note that 0 is not printed because the condition requires i > 0. Loop with a Condition If you remove the initializer and post-operator from the syntax, you get a simple construct that works based on a condition. The loop declaration in this case looks like this: i := 0 for i < 6 { fmt.Println(i) i++ } If you are familiar with other programming languages, you might recognize this as similar to a while loop. In this example, i is defined outside the loop. The for loop only has a condition, which keeps the loop running while i is less than 6. Note that the increment operation (i++), previously specified as a post-operator, is now inside the body. Sometimes, the number of iterations is unknown in advance. You can't specify a condition for ending the loop in such cases. To avoid infinite loops, Go supports the break keyword. Here's a simple example: func main() { i := 0 for { fmt.Println("Hello") if i == 5 { break } i++ } } Initially, i = 0. The loop runs indefinitely, printing "Hello" each time. However, when i reaches 5, the break statement is executed, and the program stops. RangeClause Go also provides another type of loop — the RangeClause. It is similar to ForClause, but it returns two values by default: the index of an element and its value. package main import "fmt" func main() { words := []string{"host", "man", "hostman", "cloud"} for i, word := range words { fmt.Println(i, word) } } Output: 0 host 1 man 2 hostman 3 cloud To omit the index, use an underscore _ as a placeholder: package main import "fmt" func main() { words := []string{"host", "man", "hostman", "cloud"} for _, word := range words { fmt.Println(word) } } Output: host man hostman cloud You can also use range to add elements to a list: package main import "fmt" func main() { words := []string{"host", "man", "hostman", "cloud"} for range words { words = append(words, "great") } fmt.Printf("%q\n", words) } Output: ["host" "man" "hostman" "cloud" "great" "great" "great" "great"] In this example, the word "great" is added for each element in the original length of the words slice. Suppose you have a slice of 10 zeros and need to populate it with numbers from 0 to 9: package main import "fmt" func main() { integers := make([]int, 10) fmt.Println(integers) for i := range integers { integers[i] = i } fmt.Println(integers) } [0 0 0 0 0 0 0 0 0 0] [0 1 2 3 4 5 6 7 8 9] You can use range to iterate over each character in a string: package main import "fmt" func main() { hostman := "Hostman" for _, letter := range hostman { fmt.Printf("%c\n", letter) } } Output: H o s t m a n This allows you to process each character in a string individually. Nested Constructs A for loop can be created inside another construct, making it nested. We can represent its syntax as: for { [Action] for { [Action] } } First, the outer loop starts running. It executes and then triggers the inner loop. After the inner loop finishes, the program returns to the outer loop. This process repeats as long as the given condition holds or until the program encounters a break statement. There is also a risk of creating an infinite loop, which even the powerful resources of Hostman wouldn’t handle, as the program would never terminate. To avoid this, always ensure the condition is properly checked or use the break operator. Here’s a simple example to demonstrate nested loops: package main import "fmt" func main() { numList := []int{1, 2} alphaList := []string{"a", "b", "c"} for _, i := range numList { fmt.Println(i) for _, letter := range alphaList { fmt.Println(letter) } } } Output: 1 a b c 2 a b c This example clearly demonstrates the order of operations: The first value from numList (1) is printed. The inner loop executes, printing each value from alphaList (a, b, c). The program returns to the outer loop and prints the next value from numList (2). The inner loop runs again, printing the values of alphaList (a, b, c) a second time. Conclusion Using for loops in Go is straightforward. Depending on the task, you can choose one of the three main forms of for or combine them to create nested constructs. You can control the loop's behavior by modifying the condition, initializer, and post-operator or by using break and continue statements. Nested loops provide flexibility and power but should be used carefully to avoid infinite loops or excessive computational overhead. You can deploy Go applications (such as Beego and Gin) on our app platform.
11 December 2024 · 6 min to read
Go

How to Install Go on Windows

Go, or Golang, is a high-performance, multithreaded programming language developed by Google in 2007 and released in 2009. To this day, Golang continues to gain popularity.  The Go programming language supports many operating systems, making it a versatile choice for development across various platforms. In this guide, we will walk through the step-by-step process of installing Golang on Windows. Installing Go on Windows Go supports Windows 7 and newer versions. Ensure that you have a supported version of the OS installed. In this guide, we will use Windows 11. You will also need an administrator account to configure environment variables. To install Golang on Windows: Download the installer for the latest version of Microsoft Windows from the official Go website. If needed, you can select any other available version of the language instead of the latest one. Once the file has finished downloading, run it and follow the installation wizard's instructions. If necessary, you can change the file location. This will be useful when configuring environment variables. After the installation, check if Golang was successfully installed on your system. To do this, open the terminal (Win + R → cmd) and run the following command: go version The output should show the version of Go you just installed. For example: To update Golang to a newer version on Windows, you must uninstall the old version and follow the instructions to install the new one. Now, let's move on to setting up environment variables so that Go works properly. Setting Up Environment Variables Setting up environment variables is an important step in installing Go on Windows, as it allows the operating system to determine where the necessary Go files and directories are located. For Go to work correctly, two environment variables are required: GOPATH points to where Go stores downloaded and compiled packages. PATH allows the system to find Go executable files without specifying their full paths. GOPATH First, let's set up the GOPATH environment variable. For this, you need to organize a workspace where Go files and projects will be stored. In this guide, we will create a workspace at C:\GoProject. We will also add two directories to this folder: bin – for storing executable files (binary files). Go creates an executable file and places it in this directory when you compile your project. src – for storing Go source files. All .go files will be placed here. After creating the workspace, we will set the GOPATH environment variable. To do this, go to the Control Panel → System and Security → System and click on Advanced System Settings. There is also an easier way to access system properties: open the Run window (Win + R) and enter: sysdm.cpl Click on Environment Variables, then click the New button under the User Variables section. Here, you need to fill in two fields: the variable name and its value. In the Variable name field, enter GOPATH, and in the Variable value field, enter the path to the workspace you created earlier (in our case, C:\GoProject). Click OK twice to save the changes. To verify the creation of the system variable, open the Run window (Win + R) and enter the string: %GOPATH% If everything was done correctly, your workspace will open. PATH The PATH environment variable should have been automatically added after we installed Go. To check this, go to the Control Panel → System and Security → System and click on Advanced System Settings. In the window that opens, you need to find PATH among the system variables. To view its values, double-click on it. In the new window, there should be an entry that holds the path to the Go bin folder. In our case, it is C:\Program Files\Go\bin. If your value does not match what was specified during the Go installation, change it to the correct one using the Edit button. At this point, the installation of Golang on Windows and the setup of environment variables is complete. Now we can check its functionality by writing and running our first program. Verifying Installation To check the functionality of the newly installed Golang on Windows: Сreate a test file with the .go extension in the workspace (C:\GoProject\src). For example, ExampleProgram.go. Add the following simple code: package mainimport "fmt"func main() {    fmt.Println("Hello, Go has been successfully installed into your system!")} The program should display a message confirming that Go has been successfully installed on your system. To compile and run the program, enter the following command in the terminal: go run %GOPATH%/src/ExampleProgram.go As shown in the image below, the program compiles and runs, displaying the specified text on the screen. Conclusion Installing Go on Windows is a straightforward process, involving downloading the installer, setting up environment variables, and verifying the installation. Once Go is properly configured, you can easily start developing applications. With support for multiple operating systems, Go remains a powerful and versatile language, ideal for cross-platform development. On our app platform you can deploy Golang apps, such as Beego and Gin. 
10 December 2024 · 5 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support