5 minutes read

You've already been acquainted with Go's built-in net/http package and learned that it provides HTTP client and server implementations. In this topic, you will learn about Gin, a web framework that simplifies the creation of web applications and services.

What is Gin?

Gin is a minimalistic framework designed for building high-performance web applications. The Gin framework is simple and easy to use, so it is a popular choice for developers looking to build web applications quickly and efficiently.

Now, you might be wondering why you should use a web framework like Gin instead of the built-in net/http package to create a web application? Imagine that thousands of developers are writing their implementation of a web service or resource; a web framework like Gin standardizes common operations like routing and request handling so that developers can focus on writing the unique parts of their web applications.

Some developers prefer to use frameworks like Gin because it provides simplified and standardized methods to perform specific actions; these methods also make the web app code more intuitive and readable, which is valuable when working with a team. Another reason to use the framework is support. If you have a problem using Gin, you can always ask the community or developers a question.

Gin is neither a front-end framework nor an alcoholic drink (haha). Gin is a back-end framework focused on handling requests and data processing.

Gin features

Memory — Gin uses a router that doesn't allocate memory on each request; this allows the framework to handle a large number of requests with a low memory footprint and high performance.

Testing — Gin comes with a comprehensive set of automated tests that validate if individual units of code (e.g., functions, methods) work as intended. For example, you can look at a simple test case of a GET handle in the official docs. You'll learn more about writing unit tests with Gin in future topics.

Stable — Gin's API has reached a stable state, and any new framework releases will not change or break the existing API; this provides stability and predictability for developers using Gin, as they can be confident that any code they write using the current API will continue to work in future releases of the framework.

Battle-tested — Testing and use in real-world production environments proved that Gin is reliable and robust in handling a large number of requests and different types of workloads. Apart from that, some notable companies like Alibaba and Sezzle have used Gin or have mentioned it as a part of their tech stack.

How to install Gin

First, check out your version of Golang. To install and use the Gin framework, Go version 1.16+ is required, where the Module-aware mode is enabled by default.

Gin is an external framework. Before you get started, you need to set up your environment to work. Create a new folder and then initialize Go modules:

go mod init theFirstShot

Then install the Gin framework:

go get github.com/gin-gonic/gin

And, of course, create the main.go file. That's it; you're ready to start!

First Gin application

Let's start with the classic basic ping-pong web application. The task is quite simple — create a server and a route for the endpoint /ping with the response string "pong":

package main

import (
    "github.com/gin-gonic/gin"
    "log"
    "net/http"
)

func main() {
    router := gin.Default()
    router.GET("/ping", func(context *gin.Context) {
        context.String(http.StatusOK, "pong")
    })

    err := router.Run()
    if err != nil {
        log.Fatal(err)
    }
}

Now run the above program. Pay attention to the execution behavior. The program does not stop executing. The reason is that Gin is launching a web server. While the server is running, you can send requests to it.

To send a request, you need to know at least two things: the server's address and the route. Let's define the server address first. The server starts with the router.Run() method. It's a shortcut for the http.ListenAndServe method of the built-in net/http package, that launches a http.Server and starts listening and serving HTTP requests.

If you don't specify a string with an IP address and port as an argument to router.Run(), it will start the web server at the default address 0.0.0.0:8080.

In the above program, the route is /ping — three main parameters define every route:

  • a network method (router.GET registers a route that handles incoming GET requests);

  • a route name (/ping, or you can use the plain route name ping, without the leading slash);

  • a route handler (the anonymous function associated with the router.GET method).

Now, you are ready to send your first request to the Gin web server. The complete address can be defined as 0.0.0.0:8080/ping. The 0.0.0.0 address is used to make the web server listen to all incoming requests to your PC's local host. You can send requests to 127.0.0.1:8080/ping or localhost:8080/ping, and the result will be the same. Type the request string into any browser, and you should see the pong response!

Note that if you try to open any other address in your browser, like localhost:8080/gin, or send a POST request to 0.0.0.0:8080/ping, both cases will return a 404 page not found error because there is no router with a route defined for the /gin endpoint, and there is no router with the POST method defined for the /ping endpoint. The automatic 404 page not found error is one of those little things the Gin framework does for you.

Finally, the web server will keep running until you stop the web application manually or if there is a runtime error like a failure to bind to a specific port or network connectivity problems.

Conclusion

Today you have learned how to create a simple web application using the Gin framework and learned about basic routing. Let's recap what you should know:

  • Gin is an external framework, and it needs to get installed into your Go project;

  • Gin launches a web server to run your web application;

  • To create a new route, you have to define it by specifying a network method, route name, and handler function;

  • To start a Gin web server, you need to use the Run method.

4 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo