» Go: Build a REST API with Gin » 2. Development » 2.1 Initial Version

Initial Version

Create a module

Run the go mod init command, giving it the path of the module your code will be in.

go mod init literank.com/rest-books

Its result:

go: creating new go.mod: module literank.com/rest-books

This command creates a go.mod file in which dependencies you add will be listed for tracking.

Installation

Download and install Gin framework:

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

This command updates the go.mod file and creates a go.sum file in your project.

Create main.go:

package main

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

func main() {
	// Create a new Gin router
	r := gin.Default()
	// Define a GET handler
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	// Run the server, default port is 8080
	r.Run()
}

Run the program like this:

go run main.go

You will get result lines like below:

[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    /ping                     --> 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

Your API server is runnong on port 8080 now.

Try to hit the endpoint /ping with curl command:

curl http://localhost:8080/ping

It shows:

{"message":"pong"}

Nice! Your server is doing well.

PrevNext