How to Build a REST API with Gin in Go

Web
Initialize a Go module, install Gin, define a route handler, and run the server to create a basic REST API.

Initialize a Go module, install the Gin framework, and define a handler function to create a basic REST API.

package main

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

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello World"})
	})
	r.Run(":8080")
}
  1. Create a new module and initialize it with go mod init myapi.
  2. Install the Gin library using go get -u github.com/gin-gonic/gin.
  3. Save the code above into a file named main.go.
  4. Run the server with go run main.go.