Learn about Golang through example RESTful API using Gorilla Mux

Tram Ho

1. Introduction

Hello friends, recently, I have just learned and learned more about the Golang language, today I would like to share some knowledge about this language, and in the next part of this article I will also introduce A simple RESTful API example in Golang using Gorilla Mux.

2. Golang

overview

Go was developed in 2007 by Robert Griesemer, Rob Pike and Ken Thompson at Google but launched in 2009 as an open source programming language.
Go is a new programming language designed and developed by Google. It is expected to help the software industry exploit the multi-core platform of the processor and multitask better.
Personally, I used to work on Java, when I moved to Go, I found that because Go is newer than Java, so the development community and supporting libraries are not as much as Java, but will have to code & custom is quite a lot. However, I feel that when compile & run of Go is faster than Java.
The Go documentation, describes Go as “a fast, static type, compiled language, but a dynamic, interpreted language”. Even a large Go program will be compiled within seconds.

Learn Golang

During the course of learning Golang, I folow followed A Tour of Go . This is the official Golang document for beginners, I suggest that you guys should follow this tutorial when learning Golang. In this tutorial we will learn about the structure, syntax, features of Go such as pointers, struct, slice, interface, goroutine, … These knowledge is introduced quite fully through. The examples in that tutorial.
Personally, when folow follow this tutorial, I often re-code the examples in each article, this helps to quickly get used to the syntax, and the re-coding as well as 1 time memorization of those lessons. Each tutorial will also have exercises to use with that knowledge. However, there are some articles that are quite sweet and sometimes difficult to understand, if you do not think that you can consult by searching the solutions on Goolge then reading and coding again.

Gorilla Mux

Gorilla Mux is a package library that makes it possible to implent a router & dispatcher to make incoming requests to their respective handlers.
To learn more about how to use this library will be introduced in more detail in the following example.

Go modules

There is a question, in Go, how do I manage dependencies? When developing an application, it is important to manage dependencies, so how do you do it in Go?
In Go, dependencies are stored in $GOPATH/src , you can see where your GOPATH is configured by typing go env GOPATH .
Since Go 1.11 version Go 1.11 , when a project wants to be able to use the dependencies, it is imperative that the project be installed in GOPATH, from which your project can read and use other dependencies in GOPATH.
However, after the version above, Go also introduced a way to manage new dependencies, which is Go Modules . Using Go Modules allows modules to be used when the current directory or any directory has a go.mod file, as long as the directory is outside $GOPATH/src . (Inside $GOPATH/src , for compatibility the go command will still run in the old GOPATH mode, even when go.mod is found) Starting with Go 1.13, the modules mode will be the default for all developments.
You can initialize Go modules for your application with the following command:

When your application is initialized with Go modules, Go allows your application to access and use other dependencies included in $GOPATH .
Note: If in your GOPATH there are no packages you need to use, you can get back using the following command:

3. Create RESTful API using Gorilla Mux

Now, let’s learn more about Go & Gorilla Mux through a simple REST API example like this:
TODO management application includes APIs:

  • Returns the list of TODOs
  • Get TODO information by ID
  • Create new TODO
  • Edit the content of TODO
  • Delete TODO

Directory structure

Below is the directory structure of the example:

I don’t know if the organization above is standard But when I learned about the common folder structure of a Golang project, I found this project on github about how to organize the layout of a popular Golang project. This is a basic layout for Go application projects. It is not an official standard defined by the Go; ang team. However, it is a growing set of Go project layout templates and a popular emerging template. It also has some minor improvements along with some popular support folders for any application big enough in the real world.
Next, I will go into details and explain each file one by one

go.mod & go.sum

These are the two files that the Go modules initializes for your application. Here, I named my moudle learn-golang so I will use the following command to initialize the Go modules for the application:

todo.go

The todo.go file contains the TODO object modifier that your application will work with:

In this example, I will work with a TODO object that includes ID, Name, and Content properties. We will declare the struct type as above to accompany the data type and format the field name JSON to return to the object.

data.go

data.go file is the file that manages the data of TODO object in the project. Due to this project example, I do not mention the database connection problem, so I will create the original TODO list and manage it through this data.go file.

Since we have configured the project with the Go module with the name learn-golang , having this file can easily use the Todo dto above using the import command:
import "learn-golang/pkg/dto"
func init() : this is a function that initializes the initial values ​​when the project is started, in this example it initializes a Todo list with 5 elements.

main.go

This is the main file to start the project.

By importing the github.com/gorilla/mux package, from here we can use gorilla / mux for the project.
Initialize the router using the command: mux.NewRouter()
Next is the declaration of APIs: get all Todo, get Todo by id, create, update & delete Todo. Note that the second HandleFunc of the HandleFunc method HandleFunc a function type, details of the function definition will be discussed later in the file todo_handler.go .
Finally we can start the server to let the router listen using the following command of package net/http : http.ListenAndServe(":8080", r) . The first parameter specifies that the project will start server listen on port 8080, and the second parameter is the router defined above.

todo_handler.go

As mentioned above, here is the file that handles the logic of the handle functions that will be passed to the routers:

We implemented the GetAllTodo func. In this file, we define 2 funces, responseWithJson & generateId . Func responseWithJson is a common method containing the settings so that http.ResponseWriter can change and return the response as desired. generateId is a method that automatically calculates the ID when creating a new Todo (will be used in the CreateTodo function).
Now let’s go into the details of the main funces for the other APIs:

GetTodoById

CreateTodo

UpdateTodo

DeleteTodo

3. Testing API

Now let’s test our APIs using Postman. First start the project with the following command:

Get all Todo API & Get Todo by ID API

Test API Get all Todo & API Get Todo by ID

Create Todo API

Test the Create Todo API

API Update Todo

Test the Todo Update API

Delete Todo API

4. Conclusion

Through the above article, I introduced a bit about the Golang language, how I learned this language and a small demo using Golang with Gorilla Mux to create a simple API project. Hope the above article will help you in study and work, thank you for your attention.

Share the news now

Source : Viblo