Get started with Gin framework

0
4096
Get started with Gin framework
Get started with Gin framework

Gin or Gin-gonic is one of the most popular and most feature rich web framework in Go (Golang). Let’s get started with Gin framework by creating a simple Hello World application.

Pre-requisites

Make sure you have Go v1.16+ installed in your development before moving on. You can confirm by typing:

$ go version
go version go1.18.3 darwin/arm64

In this tutorial, I’m using Go 1.18.3.

Create the project

Let’s start by creating a new Go project, please follow my commands below:

$ mkdir gin-hello

$ cd gin-hello

$ go mod init petehouston.com/gin-hello

All of those commands will create a new Go project inside a directory named gin-hello and init go.mod for dependencies.

Install Gin-gonic dependencies

Next is to get the Gin framework into the project, which can be done via this command:

$ go get github.com/gin-gonic/gin

That’s all set, we can start writing the code for the Gin framework.

Develop “Hello World” application

Create a new file main.go in the root directory, and put this bare code:

package main

func main() {
    //TODO: write main code
}

First, import the Gin framework module:

import "github.com/gin-gonic/gin"

A Gin application always starts by defining a router typed RouterGroup; by default, we can get an instance of RouterGroup by calling gin.Default():

router := gin.Default()

We then can add a GET route that returns the “Hello World” text to the browser like so:

router.GET("/", func(context *gin.Context) {
	context.String(200, "Hello world!")
})

Afterward, the Gin server can start by calling the Run() method:

err := router.Run()
if err != nil {
	panic("[Error] failed to start Gin server due to: " + err.Error())
	return
}

Let’s build and run the project:

$ go run main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080

You can open browser (ex. Chrome, Firefox, Safari…) and visit the url localhost:8080, you expect to see the Hello world! text showing on the page.

The first parameter passed into the context.String() method is the number of HTTP status code; instead of using hard-coded number, you can use the status constants defined in net/http package.

The complete code of the “Hello World’ application will look like this:

package main

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

func main() {
	router := gin.Default()
	router.GET("/", func(context *gin.Context) {
		context.String(http.StatusOK, "Hello world!")
	})
	err := router.Run()
	if err != nil {
		panic("[Error] failed to start Gin server due to: " + err.Error())
		return
	}
}

Customize the port

On the extra note, by default, Gin will run server at port 8080, you can also change the port by passing it into the Run() method like:

router.Run(":8888")

Then Gin server will start application at port 8888.

Conclusion

There you go, I have shown you how to create the first web application to get started with Gin framework.

You can also take a look at complete project at: https://github.com/petehouston/golang-sample-code/tree/dev/gin-hello

See you in future tutorials!