Controllers
Handle HTTP requests with controller functions and resource controllers.
Controllers handle incoming HTTP requests and return responses. In RapidGo, controllers are either standalone handler functions or structs implementing the ResourceController interface.
Function Controllers
The simplest approach — a function with a *gin.Context parameter:
package controllers
import (
"net/http"
"github.com/gin-gonic/gin"
)
func Home(c *gin.Context) {
c.HTML(http.StatusOK, "pages/home.html", gin.H{
"title": "Welcome",
})
}
func ListUsers(c *gin.Context) {
var users []models.User
db.Find(&users)
c.JSON(http.StatusOK, users)
}
Resource Controllers
Implement the ResourceController interface for full CRUD:
type PostController struct{}
func (p *PostController) Index(c *gin.Context) { /* GET /posts */ }
func (p *PostController) Create(c *gin.Context) { /* GET /posts/create */ }
func (p *PostController) Store(c *gin.Context) { /* POST /posts */ }
func (p *PostController) Show(c *gin.Context) { /* GET /posts/:id */ }
func (p *PostController) Edit(c *gin.Context) { /* GET /posts/:id/edit */ }
func (p *PostController) Update(c *gin.Context) { /* PUT /posts/:id */ }
func (p *PostController) Destroy(c *gin.Context) { /* DELETE /posts/:id */ }
Register it:
r.Resource("/posts", &controllers.PostController{})
// or for APIs (no create/edit form routes):
api.APIResource("/posts", &controllers.PostController{})
Request Data
// Form data
name := c.PostForm("name")
email := c.PostForm("email")
// JSON body
var input struct {
Name string `json:"name"`
Email string `json:"email"`
}
c.ShouldBindJSON(&input)
// URL parameters
id := c.Param("id")
// Query string
page := c.DefaultQuery("page", "1")
Responses
// JSON
c.JSON(http.StatusOK, gin.H{"message": "success"})
// HTML template
c.HTML(http.StatusOK, "pages/show.html", gin.H{"post": post})
// Redirect
c.Redirect(http.StatusSeeOther, "/posts")
// Error
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
Scaffolding
Generate a new controller with the CLI:
go run cmd/main.go make:controller User
# Creates: http/controllers/user.go