First we need to give our Web App a name. We will be making a simple blog, so let’s call it RGB (React Gin Blog).
We will start by making project root directory inside of ~/go/src/
and making it our current working directory.
cd ~/go/src
mkdir rgb
cd rgb
Our first dependency is Gin framework. You can download it by running go get github.com/gin-gonic/gin
if you don’t have it already. Before writing our first backend source file, we need to crate go.mod
file in project root directory needed by Golang to find and import required dependencies. Content of that file will for now be:
module rgb
go 1.16
require github.com/gin-gonic/gin v1.6.3
Now let’s make our app entry point, main.go
file:
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// Creates default gin router with Logger and Recovery middleware already attached
router := gin.Default()
// Create API route group
api := router.Group("/api")
{
// Add /hello GET route to router and define route handler function
api.GET("/hello", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{"msg": "world"})
})
}
router.NoRoute(func(ctx *gin.Context) { ctx.JSON(http.StatusNotFound, gin.H{}) })
// Start listening and serving requests
router.Run(":8080")
}
And that’s it. We can now start our server by running go run main.go
Verify that server is running by opening localhost:8080/api/hello
in your favorite web browser. If server is working you will see {"msg":"world"}
.