How do I build a REST API with Gin in Go?

Building a REST API with Gin in Go is a straightforward process. Gin is a high-performance web framework that allows you to create web applications quickly and efficiently. Below, you will find step-by-step instructions to create a simple REST API using Gin.

Step 1: Install Gin

To start, you need to install Gin. Open your terminal and run the following command:

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

Step 2: Create the Main File

Create a new Go file (e.g., main.go) and set up the basic structure:

package main import ( "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/api/hello", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello, World!"}) }) router.Run(":8080") }

Step 3: Run the API

To run your API, execute the following command in the terminal:

go run main.go

Step 4: Test Your API

Open your web browser or use a tool like Postman to test the endpoint:

GET http://localhost:8080/api/hello

You should receive a JSON response:

{"message": "Hello, World!"}

Go Gin REST API Go framework web development JSON response HTTP server