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")
}
- Create a new module and initialize it with
go mod init myapi. - Install the Gin library using
go get -u github.com/gin-gonic/gin. - Save the code above into a file named
main.go. - Run the server with
go run main.go.