- read

Setting Up a Basic Golang Project with Gin Framework and Test Cases

Abhishek Ranjan 3

Introduction

Gin is a high-performance web framework for the Go programming language. It is lightweight, fast, and easy to use, making it an ideal choice for building web applications. In this article, we will demonstrate how to set up a basic Golang project with the Gin framework and write test cases for the implemented features.

Prerequisites

To follow along, you need to have the following installed on your system:

  1. Go (version 1.16 or higher)
  2. A text editor or IDE for writing Go code (e.g., Visual Studio Code, GoLand, or Sublime Text)

Step 1: Create a New Go Project

Create a new directory for your project and navigate to it in the terminal:

$ mkdir my-gin-project
$ cd my-gin-project

Initialize the project as a Go module:

$ go mod init github.com/yourusername/my-gin-project

Step 2: Install Gin Framework

To install the Gin framework, run the following command:

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

Step 3: Create a Basic Gin Application

Create a new file called main.go and add the following code:

package main

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

func main() {
router := gin.Default()

router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})

router.Run(":8080")
}

This code sets up a basic Gin application with a single route, /ping, which returns a JSON object containing the message "pong".

Step 4: Run the Application

To run the application, execute the following command:

$ go run main.go

You should now be able to access the /ping endpoint at http://localhost:8080/ping.

Step 5: Write Test Cases

Create a new file called main_test.go and add the following code:

package main

import (
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)

func TestPingRoute(t *testing.T) {
gin.SetMode(gin.TestMode)

router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/ping", nil)
router.ServeHTTP(w, req)

assert.Equal(t, 200, w.Code)

respBody, err := ioutil.ReadAll(w.Body)
assert.Nil(t, err)
assert.Equal(t, `{"message":"pong"}`, string(respBody))
}

This code defines a test function TestPingRoute that tests the /ping route. It sets up a test HTTP server and sends a GET request to the /ping route. It then checks whether the response status code is 200 and whether the response body matches the expected JSON object.

Step 6: Install Testify Package

To simplify testing, we use the Testify package for assertions. Install it with the following command:

$ go get -u github.com/stretchr/testify

Step 7: Run the Test Cases

To run the test cases, execute the following command:

$ go test -v

If everything is set up correctly, you should see output indicating that the test has passed:

=== RUN