[NEW] Basic gets a boost: Announcing major upgrades to our free AI code assistant
Home / Blog /
Golang Gin: A comprehensive tutorial
//

Golang Gin: A comprehensive tutorial

//
Tabnine Team /
6 minutes /
May 22, 2022

Native apps are all the rage, but web apps are better for accessibility and for being cross-device and operating system agnostic. According to Forbes, the number of apps in both Android and Apple saw steady declines in their app stores. Apple’s descent started in 2017. Meanwhile, Android’s app store peaked in March 2018 at 3.6 million apps. While there are genuine reasons for this, such as old and unsupported apps being deleted and fewer releases, the web and its existence in browsers remains the first point of contact for many users.

Golang may play a role in helping to shape and improve the web in the future by providing a robust, efficient, and easy-to-use programming language that developers can use to create a wide range of web-based applications and services. Golang’s focus on simplicity, stability, and reliability may make it a popular choice for web developers looking for a reliable and efficient language for their projects.

While Golang is the programming language, it is not complete without a framework to keep everything in line. Gin is a web framework written in Golang. The primary perk of using Gin is getting just enough infrastructure to get your application up and running.

But what exactly is Gin? How does it work? This tutorial will explain the basics of using Gin, such as installation, routing, custom rendering, reusable templating, installing dependencies, and using middleware.

What is Gin in Golang?

Golang is a programming language created by Google. It is a statically typed, compiled language with syntax similar to that of C. Gin is a Go web framework designed to be easy to use and fast.

Gin is built around a simple idea: it is possible to write web applications without much boilerplate code using reflect. This means that your code will be concise and easy to read.

Gin comes with many features that make development faster and easier. These include

  • A built-in web server
  • Automatic routing
  • A set of tools for handling requests and responses
  • Middleware for adding functionality
  • A built-in logger
  • Support for templating

Developers can use Gin in a variety of ways, such as to develop web applications, API servers, or even command-line tools.

Why use Gin?

If you’re looking for a fast and lightweight web framework, Golang Gin is a great option. It’s easy to use and has a great community behind it. Here are some reasons why you should use Golang Gin.

  • Gin is fast: Golang Gin is one of the fastest web frameworks available. It’s built on top of the powerful Gin gopher library, making it very quick and efficient.
  • Gin is lightweight: Another great thing about Golang Gin is that it’s very lightweight, making it ideal for building small and light web applications.
  • Gin is easy to use: Golang Gin is easy to use and has great documentation. If you’re new to web development, you’ll find it very straightforward to get started with Gin.
  • Golang has a great community: Golang Gin has a great community behind it. Many Gin developers are always willing to help and contribute.
  • Golang and Gin are open source: Golang Gin is open source and released under the MIT license, so you can use it for any purpose, including commercial projects.

Keep up with software development’s evolving field

To remain relevant in the constantly changing landscape of software development, it is essential to stay up-to-date with the latest advancements and trends. Keeping abreast of new technologies and practices ensures that you are equipped with the knowledge and skills needed to succeed in this dynamic field. Learn more about how to utilize AI to optimize your software engineering in 2023.

Golang Gin – A Comprehensive Starter Tutorial

Installing Golang Gin

Assuming you have a working Go installation, this should get you up and running with Gin, create a new project directory and change into it:

mkdir myproject cd myproject

Download and install Gin:

go get github.com/gin-gonic/gin

Create a main.go file with the following contents:

package main
import "github.com/gin-gonic/gin"​
func main() {
    r: = gin.Default()
    r.GET("/tab", func(c * gin.Context) {
        c.JSON(200, gin.H {
            "message": "nine",
        })
    })
    r.Run()
    // listen and serve on 0.0.0.0:8080
}

Run the server:

go run main.go

You should now be able to access the server at http://localhost:8080/tab.

Routing with Golang Gin

Routing is matching a URL path to a handler. In gin, a router matches incoming requests to the appropriate handler. A router is initialized with a root path and an array of routes. Each route consists of a method, a path, and a handler. The handler is a function that is invoked when a match is found.

Incoming requests are matched against the routes in the router. If a match is found, the corresponding handler is invoked. If no match is found, a 404 Not Found status is returned.

Gin also provides a way to group routes. A group is a collection of routes that share a common root path. Groups can be nested to create more complex routing structures.

To create a new router, use the New() function:

router := gin.New()

To add routes to the router, use the router’s Handle() or HandleFunc() methods:

router.Handle("GET", "/", homeHandler)
​
router.HandleFunc("POST", "/login", loginHandler)

The first argument to Handle() and HandleFunc() is the HTTP method. The second argument is the URL path. The third argument is the handler function.

Handlers can be any type of function, but gin provides a few helper functions designed specifically for gin use. You can find these helper functions in the gin.HandlerFunc type.

To invoke a handler, use the router’s ServeHTTP() method:

router.ServeHTTP(w, r)

The ServeHTTP() method takes an http.ResponseWriter and an http.Request as arguments. It matches the incoming request to a route and calls the corresponding handler.

Gin also provides a way to retrieve the URL for a given handler, which can be useful for creating links in your templates. The Url() method takes a handler and returns the URL for that handler:

url := router.Url("homeHandler")

Custom rendering and creating reusable templates in Golang Gin

To render your own HTML templates in Gin, you need to first set the HTMLRender variable to point to your own HTMLRender instance. You can do this by passing in a pointer to your custom HTMLRender instance to the gin.SetHTMLTemplate() function.

Once you have set the HTMLRender variable, you can then call the gin.HTML() function to render your template. The HTML() function takes in two parameters: the name of the template to render, and a data interface{} that will be passed to the template.

Here is a simple example:

// main.go
​
package main
​
import (
  "github.com/gin-gonic/gin"
)
​
func main() {
  r := gin.Default()
  r.SetHTMLTemplate(myCustomHTMLRender)
  r.GET("/", func(c *gin.Context) {
  c.HTML(200, "index.tmpl", gin.H{
  "title": "Welcome to TabNine",
  })
  })
  r.Run()
}
​
// myCustomHTMLRender.go
​
package main
​
import (
  "github.com/gin-gonic/gin"
  "html/template"
)
​
func myCustomHTMLRender() gin.HTMLRender {
  return &MyCustomHTMLRender{
  templates: template.Must(template.ParseFiles(
  "path/to/your/template1.tmpl",
  "path/to/your/template2.tmpl",
  )),
  }
}
​
type MyCustomHTMLRender struct {
  templates *template.Template
}
​
func (r *MyCustomHTMLRender) Instance(name string, data interface{}) gin.HTMLRender {
  instance := &MyCustomHTMLRender{
  templates: r.templates.Clone(),
  }
  instance.templates.ExecuteTemplate(writer, name, data)
  return instance
}

Middleware with Golang Gin

A middleware is a function that can be used to modify the behavior of an HTTP request handler. Gin provides a convenient way to register middleware.

For example, let’s say we want to log all requests to our web application. We can create a middleware function to do that.

func Logger() gin.HandlerFunc {
    return func(c *gin.Context) {
​
        // Get the client IP address
        clientIP := c.ClientIP()
​
        // Get the current time
        now := time.Now()
​
        // Log the request
        log.Printf("[%s] %s %s %s", now.Format(time.RFC3339), c.Request.Method, c.Request.URL.Path, clientIP)
​
        // Proceed to the next handler
        c.Next()
    }
}

Then, we can register the middleware function with Gin.

router := gin.Default()
router.Use(Logger())
router.Run(":8080")

That’s it! Gin will now log all requests to our web application.

Installing dependencies in Golang Gin

Installing dependencies in Golang Gin is pretty straightforward. All you need to do is run the following command:

go get github.com/gin-gonic/gin

This will fetch the latest version of the Gin framework and install it in your $GOPATH.

Wrapping up

With the ever-growing demand for faster and more accurate software development, the need for speed and accuracy in coding has never been more important. Tabnine is an AI-based auto-completion tool that uses machine learning to constantly improve code completion suggestions, making them more and more accurate over time. 

It also offers a wide range of features that make it extremely fast and easy to use, such as instant results, fuzzy matching, and support for over 50 programming languages. Working faster and more accurately is the goal of any developer. If you’re looking to improve productivity and accuracy, give Tabnine a try!

Tabnine

Tabnine is an intelligent, AI-driven code completion tool that can cut your coding time, reduce mistakes, and make best practice suggestions.

[cta_btn url=”https://www.tabnine.com/pricing/landing” label=”Start a free trial”]