Hands-on with Golang: Building Our First Application

Dmytro Shamenko
5 min readJul 25, 2023

--

Our journey towards building a Wishlist application now brings us to a critical stage — getting hands-on with coding. In this article, we’ll use Golang and a framework called Echo to build our server-side logic.

Remember, you don’t have to use Golang if you’re comfortable with another language. The language you choose won’t impact the overarching journey towards becoming proficient in DevOps.

The Basics of a Golang Application

Golang applications, at their simplest, can start with a single .go file. For our purpose, let’s create a file named wishlist.go within our wishlist-server directory (either a folder or a repository, depending on your previous choice).

To build and run Golang applications, you first need to install Golang on your computer. You can find the official installation guide here.

Monorepo Concept

If you chose to start with a single repository, congratulations! You’re already familiar with the concept of a monorepo. This approach, where all codebase lives within a single repository, is popular in the tech industry and comes with its benefits, such as simplified dependency management and unified versioning.

Adding Our First Endpoint

With the wishlist.go file created, let’s add some code. We will generate a simple server using the Echo framework and create a /health endpoint.

package main

import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)

// The main function is the entry point of the application.
// This function will initialize a new Echo instance, set up the routes, and start the server.
func main() {
// Create a new instance of Echo.
e := echo.New()
// Register middleware for logging and recovering from panics.
// Logger middleware logs the information about each HTTP request.
// Recover middleware recovers from any panics and writes a 500 if there was one.
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Set up the routes.
// Health check route.
e.GET("/health", healthCheck)
// Start the server and listen on port 1323.
// The application will terminate if it fails to start the server.
e.Logger.Fatal(e.Start(":1323"))
}

// healthCheck is a handler function that responds to HTTP requests with a health check status.
// It simply returns a JSON response with a status field set to "OK".
// This can be used by services and load balancers to check the health of the application.
//
// Parameters:
// c: An echo.Context object which holds request and response objects, path parameters, data, registered handler.
//
// Returns:
// error: An error object that can be thrown if there are any errors during the execution of the function.
func healthCheck(c echo.Context) error {
// Prepare a data map with a single key-value pair where key is "status" and value is "OK".
data := map[string]interface{}{
"status": "OK",
}

// Use the echo.Context object to send a JSON response.
// http.StatusOK sets the HTTP status code to 200.
// The second parameter is the data to be sent in the response body.
return c.JSON(http.StatusOK, data)
}

This is the first version of the server, which you can run using go run wishlist.go, but to be able do so, you need initialise your Go project.

Understanding go mod

go mod is a module manager that was introduced in Go 1.11. It is a replacement for the old way of managing dependencies (like dep or glide). With go mod, you can easily handle the versions of the libraries your project relies on, even in large and complex codebases.

Modules are collections of Go packages stored in a file tree with a go.mod file at the root. The go.mod file defines the module’s module path, which is its identity and its dependency requirements, which are the other modules needed for a successful build.

The Power of go mod init

o start using go mod in your project, you’ll first run the go mod init command. This command creates a new go.mod file in your current directory, initialising your project as a Go module. The go.mod file will also contain the module path, which typically is the repository location.

Try running the following command at the root of your project:

go mod init github.com/yourusername/wishlist-server

Taking Advantage of go mod tidy

Once you’ve initialised your Go module, you can use the go mod tidy command to automatically fetch the dependencies of your project and update your go.mod file.

This command ensures that your go.mod file matches the actual dependencies of your project’s source code. It adds missing modules necessary to build the current module’s packages and dependencies, and it removes unused modules that don’t provide any relevant packages.

By running go mod tidy, you can keep your project clean and avoid unnecessary dependencies.

Running the Server

Once you’ve written the code, you can run the server using the go run command. To validate that our server and the /health endpoint are working as expected, we’ll use a command-line tool called `curl` or API testing tools like Postman or Insomnia.

In one tab of the terminal you can run

$ go run wishlist.go
____ __
/ __/___/ / ___
/ _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.10.2
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
O\
⇨ http server started on [::]:1323

and in a split window or another tab you can run curl

$ curl -Iv -X GET http://127.0.0.1:1323/health
* Trying 127.0.0.1:1323...
* Connected to 127.0.0.1 (127.0.0.1) port 1323 (#0)
> GET /health HTTP/1.1
> Host: 127.0.0.1:1323
> User-Agent: curl/7.88.1
> Accept: */*
>
< HTTP/1.1 200 OK
HTTP/1.1 200 OK
< Content-Type: application/json; charset=UTF-8
Content-Type: application/json; charset=UTF-8
< Date: Tue, 11 Jul 2023 12:21:14 GMT
Date: Tue, 11 Jul 2023 12:21:14 GMT
< Content-Length: 16
Content-Length: 16

You will be able to see that request are logged on a server

{"time":"2023-07-11T15:21:14.802522+03:00","id":"","remote_ip":"127.0.0.1","host":"127.0.0.1:1323","method":"GET","uri":"/health","user_agent":"curl/7.88.1","status":200,"error":"","latency":59917,"latency_human":"59.917µs","bytes_in":0,"bytes_out":16}

Feel free to learn more about user_agents and methods on your free time.

What are Postman and Insomnia?

Postman and Insomnia are powerful tools for testing APIs. They provide a user-friendly interface that allows you to send HTTP requests to a server and inspect responses.

Curl, on the other hand, is a command-line tool used to transfer data using various network protocols. While curl is versatile and powerful, Postman and Insomnia offer a more interactive and user-friendly interface, making them popular choices for testing and debugging APIs.

In our next article, we’ll dive deeper into working with these tools, making HTTP requests, and understanding the responses. Stay tuned as we continue to build our Wishlist application piece by piece!

--

--

Dmytro Shamenko

Software Engineer with more than ten years of experience. Systems Architect expertise. DevOps methodology & Golang fan. www.linkedin.com/in/dmitriyshamenko