7、Go Gin 创建处理函数

在 Gin 框架中,自定义处理函数是编写 Web 应用的核心部分。这些函数负责处理具体的 HTTP 请求,执行业务逻辑,并生成响应。 

一、基本处理函数

Gin 使用 gin.HandlerFunc 类型表示处理函数,这是一个接收两个参数(*gin.Context 和一个错误)的函数,但实际上 Gin 处理函数通常只需要 *gin.Context 参数。*gin.Context 包含了请求和响应的所有上下文信息,包括请求参数、请求头、响应写入器等。

1、创建处理函数

func helloWorld(c *gin.Context) {
    // 从请求中获取参数、执行业务逻辑等
    name := c.Query("name") // 获取查询参数
    if name == "" {
        name = "World"
    }
    
    // 设置响应内容和状态码
    c.JSON(http.StatusOK, gin.H{
        "message": fmt.Sprintf("Hello, %s!", name),
    })
}

2、注册处理函数

创建好处理函数后,需要将其注册到某个路由上,以便 Gin 能够根据请求的 URL 调用相应的处理逻辑。

package main

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

func main() {
    r := gin.Default()

    // 将上面定义的处理函数绑定到 /hello 路由上
    r.GET("/hello", helloWorld)

    // 启动服务器
    r.Run(":8080")
}

3、使用路由参数

在处理函数中,你还可以访问路由参数,这是 URL 中动态的部分。

func userHandler(c *gin.Context) {
    userId := c.Param("userId") // 获取路由参数
    c.JSON(http.StatusOK, gin.H{"message": "User ID: " + userId})
}

// 注册时包含路由参数
r.GET("/users/:userId", userHandler)

4、处理表单和JSON数据

Gin 支持轻松处理 POST 请求中的表单数据和 JSON 数据。

  • 表单数据示例:
func formHandler(c *gin.Context) {
    name := c.PostForm("name") // 获取表单字段
    c.JSON(http.StatusOK, gin.H{"received": name})
}
  • JSON 数据示例:
type Person struct {
    Name string `json:"name"`
}

func jsonHandler(c *gin.Context) {
    var person Person
    if err := c.ShouldBindJSON(&person); err == nil {
        c.JSON(http.StatusOK, gin.H{"message": "Hello, " + person.Name})
    } else {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    }
}

通过以上示例,你可以看到 Gin 提供了简洁的 API 来定义和使用自定义处理函数,覆盖了从基本路由处理到复杂数据绑定的各种需求。

二、创建处理函数分组例子

代码结构

创建处理函数案例代码

admin/loginController.go

package admin

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

type LoginController struct {
}

func (con LoginController) Index(c *gin.Context) {
	c.String(200, "登录首页")
}

 admin/roteController.go

package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type RoteController struct {
}

func (con RoteController) Index(c *gin.Context) {
	c.String(http.StatusOK, "角色列表")
}

func (con RoteController) Add(c *gin.Context) {
	c.String(http.StatusOK, "添加角色")
}

func (con RoteController) Edit(c *gin.Context) {
	c.String(http.StatusOK, "角色编辑")
}

admin/userController.go 

package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type UserController struct {
}

func (con UserController) Index(c *gin.Context) {
	c.String(http.StatusOK, "用户列表")
}

func (con UserController) Add(c *gin.Context) {
	c.String(http.StatusOK, "新增用户")
}

func (con UserController) Edit(c *gin.Context) {
	c.String(http.StatusOK, "编辑用户")
}

 routers/adminRouters.go

package routers

import (
	"gin-mall/controller/admin"
	"github.com/gin-gonic/gin"
)

// AdminRouters 设置admin后台路由
func AdminRouters(r *gin.Engine) {
	adminRouters := r.Group("/admin")
	{
		adminRouters.GET("/", admin.LoginController{}.Index) // 实例化处理函数,并访问其中方法

		adminRouters.GET("/user", admin.UserController{}.Index)
		adminRouters.GET("/user/add", admin.UserController{}.Add)
		adminRouters.GET("/user/edit", admin.UserController{}.Edit)

		adminRouters.GET("/rote", admin.RoteController{}.Index)
		adminRouters.GET("/rote/add", admin.RoteController{}.Add)
		adminRouters.GET("/rote/edit", admin.RoteController{}.Edit)
	}
}

 main.go

package main

import (
	"gin-mall/routers"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	//注册路由
	routers.AdminRouters(r)

	r.Run()
}

 三、处理函数继承

代码结构

 处理函数继承案例代码

controller/admin/userController.go

package admin

import (
	"gin-mall/controller/base"
	"github.com/gin-gonic/gin"
)

// UserController 定义一个UserController结构体,可以实例化结构体访问里面的方法
type UserController struct {
	base.BaseController // 继承基础处理函数
}

func (con UserController) Index(c *gin.Context) {
	con.Success(c)
}

func (con UserController) Add(c *gin.Context) {
	c.String(200, "新增用户")
}

controller/base/baseController.go

package base

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// BaseController 基础处理函数
type BaseController struct {
}

func (con BaseController) Success(c *gin.Context) {
	c.String(http.StatusOK, "成功")
}

func (con BaseController) Error(c *gin.Context) {
	c.String(http.StatusOK, "失败")
}

routers/adminRouters.go

package routers

import (
	"gin-mall/controller/admin"
	"github.com/gin-gonic/gin"
)

// AdminRouters 设置admin后台路由
func AdminRouters(r *gin.Engine) {
	adminRouters := r.Group("/admin")
	{
		adminRouters.GET("/user", admin.UserController{}.Index)
		adminRouters.GET("/user/add", admin.UserController{}.Add)
	}
}

main.go

package main

import (
	"gin-mall/routers"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	//注册路由
	routers.AdminRouters(r)

	r.Run()
}

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值