How to Create a New Go Language Project

In Golang on 2~4 minutes
How to Create a New Go Language Project

Before creating your first Go language project, make sure that you have installed the Go language in your system. Open a new terminal window and run the following command.

go version

It should print the Go language version that you have installed in your system or otherwise install the Go language before proceeding. If you are using VSCode for code editing, make sure to install and activate the VSCode Go extension.

Create A New Go Language Project

Usually, Go language projects can be created either from scratch by yourself or start with a project which is already existing in a repository somewhere like Github. First, you will be able to learn how to create a Go project from scratch and then from a sample project existing in a repository.

Start A Go Language Project From Scratch

First, create a new directory for the Go project and go into the directory created.

mkdir hello-world

cd hello-world

Create the project module with the go mod init command. We need to provide a module path for the go mod init command. Usually, it is the URL where you publish your project. For example, if you are going to host your code in github.com/devtonighthq/hello-world, you can run the go mod init command like below.

go mod init github.com/username/hello-world

It will create a file called go.mod. Initially, the go.mod file will contain the information about the Go module path and the Go language version. When you add more dependencies to the project, they will be mentioned in this file.

Create the main.go file and add the following code to it.

package main

import "fmt"

func main() {
    fmt.PrintLn("Hello world!");
}

Start A Go Language Project From A Repository

As explained earlier, you can create a Go language project by using an existing Go language project. First, download it or clone it if it is a Git repository like this.

git clone https://github.com/username/go-repo.git

Go into the project directory and run the go mod download command to download the necessary dependencies of the project. We can use the optional -x flag to print the progress.

go mod download -x

Run The Go Application

This command will run the Go application.

go run main.go

Build The Go Application

This command will create a compiled executable file of the Go application.

go build

Run the compiled executable file created in the previous step like this.

./executable-file