gin网络请求与路由处理

创建 Engine

在 gin 框架中,gin.Default() 和 gin.New() 的区别在于 gin.Default() 也使用 gin.New() 创建 engine 实例,但是会默认使用 Logger 和 Recovery 中间件

engine1 := gin.Default()
engine2 := gin.Default()

Logger 负责进行打印并输出日志的中间件

Recovery 作用是如果程序执行过程中遇到了panic 中断了服务,Recovery 会恢复程序执行,并且返回 500 服务器内部错误

通用处理

engine 中使用 Handle 方法进行 http 请求的处理。

func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
	if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {
		panic("http method " + httpMethod + " is not valid")
	}
	return group.handle(httpMethod, relativePath, handlers)
}
  • httpMethod 第一个参数表示要处理的HTTP请求类型,是GET、POST等八种情况的一种
  • relativePath 表示要解析的路由/接口
  • handlers 表示处理对应请求的代码的定义

GET

                                     //c 对应 context
    engine.Handle("GET","/hello",func(c *gin.Context) {
            //当前访问的路由
            path:=c.FullPath()
            fmt.Println(path)

            //寻找查询字符串的参数 参数名称   默认值
            name:=c.DefaultQuery( "name" , "hello")
            fmt.Println(name)

            //返回的JSON
            c.JSON(200,gin.H{
                    "message":"wowwuao",
            })
    })

POST

    engine.Handle("POST","/login",func(c *gin.Context) {

            //根据 key 在提交的表单数据中寻找对应值
            username:=c.PostForm("username")
            password:=c.PostForm("password")

            c.Writer.WriteString("用户名:"+username+" 密码:"+password)
    })

分类处理

在 engine 中包含了GET、POST、DELETE 方法等与 http 请求对应的方法

GET

    engine.GET("/hello",func(c *gin.Context) {
            fmt.Println(c.FullPath())

            //除了 c.DefaultQuery方法获取请求携带的数据外,
            //还可以使用c.Query获取GET请求携带的参数
            username:=c.Query("name")
            fmt.Println(username)
            c.Writer.WriteString("Hello "+username)
    })

POST

    engine.POST("/login",func(c *gin.Context) {
            fmt.Println(c.FullPath())
                         //根据字符串是否存在返回bool值
            username,exist:=c.GetPostForm("username")
            if exist{
                    fmt.Println(username)
            }
            password,exist:=c.GetPostForm("password")
            if exist{
                    fmt.Println(password)
            }
            c.Writer.WriteString(username+"登录了")
    })

DELETE

    engine.DELETE("/user/:id",func(c *gin.Context) {
            //通过路由规则中的 path 加上占位符 : 
            //表示url此位置的数据当作此属性名来解析
            userID:=c.Param("id")
            fmt.Println(userID)
            c.Writer.WriteString("删除用户ID:"+userID)
    })

版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/UPCwa162/article/details/122934746