apps/api-go
|
|--------> cmd/server
|--------> main.go
|--------> internal/routes
|---------> health.go
|---------> websites.go
|---------> router.go
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",
})
}
r *gin.RouterGroup is a pointer to the group of routes that shares a common base path and middleware.r.basePath + "/health"c *gin.Context is the core object for handling a single HTTP request in Gin.
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",
})
}
r.basePath + "/websites"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:
/api/v1)main.go