- Create a folder api_demo. Go inside the folder with command line cd api_demo.
- Initialize a go project with command “go mod init api_demo”. This will create go.mod and go.sum files in the folder.
- Run command “go get github.com/gin-gonic/gin”
- We create two files main.go and Greeting.go
// main.go
package main
import (
"fmt"
"log"
"github.com/gin-gonic/gin"
)
func main() {
router := NewRouter()
fmt.Printf("Server Started.")
log.Fatal(router.Run(":8000"))
}
func NewRouter() *gin.Engine {
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pongs",
})
})
router.GET("/greeting", GreetingHandler())
return router
}
//Greeting.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func GreetingHandler() gin.HandlerFunc {
fn := func(c *gin.Context) {
var jResponse struct {
Message string `json:"msg"`
}
jResponse.Message = "Hello !"
c.IndentedJSON(http.StatusOK, jResponse)
}
return gin.HandlerFunc(fn)
}
5. We can now run files with command “go run main.go Greeting.go“. We will see that the server is started on port 8000 as configured in code. You will see “Listening and serving HTTP on :8000” on the command line.
6. Now we can test the code on browser. We have configured two urls : /ping and /greeting.
7. On http://localhost:8000/ping we can see the below json on the browser
{"message":"pongs"}
8. On http://localhost:8000/greeting we can see the below json on the browser.
{ "msg": "Hello !" }
The basic framework set up is ready.