apps/api-go
|
|--------> cmd/server
							|--------> main.go
|--------> internal/routes
							|---------> health.go
							|---------> websites.go
							|---------> router.go

Step 1 : Writing Routers

health.go

package routes

import (
	"net/http"

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

func RegisterHealthRouter(r *gin.RouterGroup) {
	health := r.Group("/health") // Creates a new RouterGroup called health
	health.GET("/", getHealthStatus) // Registers a route on the health group
}

func getHealthStatus(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
	})
}

image.png

websites.go

package routes

// Fetching an External Package in Go
// go get github.com/gin-gonic/gin ( Downloads gin and its dependencies )
// updates go.mod
import (
	"net/http"

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

func RegisterWebsitesRouter(r *gin.RouterGroup) { // gin.RouterGroup : organises the routes
	websites := r.Group("/websites")
	websites.GET("/", getWebsites)
	websites.POST("/", createWebsite)
}

// Handler Fn
func getWebsites(c *gin.Context) { // gin.Context : single HTTP request + response ( lives only during that request )
	c.JSON(http.StatusOK, gin.H{
		"message": "List all websites",
	})
}

func createWebsite(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"message": "Create website",
	})
}

Step 2 : Wiring routes together

router.go

package routes

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

func RegisterRouter(r *gin.Engine) {
	v1 := r.Group("/api/v1") // gin.Engine : Builds the server

	// Attach routes to the engine
	RegisterWebsitesRouter(v1)
	RegisterHealthRouter(v1) 
}

router.go is the central place where your application’s routes are wired together and attached to the Gin server.

It:

Step 3 : Bootstrap your application at main.go