广告
返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >二、Gin 路由(Route)和获取请求参数的方法
  • 392
分享到

二、Gin 路由(Route)和获取请求参数的方法

2024-04-02 19:04:59 392人浏览 独家记忆
摘要

路由(Route)方法 支持方法 路由方法有 GET, POST, PUT, PATCH, DELETE 和 OPTioNS,当然匹配所有类型的请求方法是 Any package main import ( "GitHu

路由(Route)方法

支持方法

路由方法有 GET, POST, PUT, PATCH, DELETE 和 OPTioNS,当然匹配所有类型的请求方法是 Any

package main

import (
    "GitHub.com/gin-Gonic/gin"
)

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

    r.Any("/ping", anything)
    // r.POST("/post", posting)
	// r.PUT("/put", putting)
	// r.DELETE("/delete", deleting)
	// r.PATCH("/patch", patching)
	// r.HEAD("/head", head)
	// r.OPTIONS("/options", options)

    r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}

func anything(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "pong",
    })
}

go run demo.go 启动服务后,执行如下命令:

% curl -X POST "Http://localhost:8080/ping"
{"message":"pong"}

解析动态路径参数

当我们需要动态参数的路由时,如 /user/:id,通过调用不同的参数 :id 动态获取相应的用户信息。其中 /user/:id/*type,*type 的参数为可选。

    r.GET("/user/:id", func(c *gin.Context) {
        id := c.Param("id")
        c.jsON(200, gin.H{
            "id": id,
        })
    })

获取结果

% curl  "http://localhost:8080/user/1" 
{"id":"1"}%

获取参数

1.获取Query参数

    // 匹配 /search?keyWord=xxx&weight=xxx ,weight可选
    r.GET("/search", func(c *gin.Context) {
        keyword := c.Query("keyword")
        weight := c.DefaultQuery("weight", "")
        c.JSON(200, gin.H{
            "keyword": keyword,
            "weight":  weight,
        })
    })

获取结果

% curl  "http://localhost:8080/search?keyword=aaa&weight=xxx"
{"keyword":"aaa","weight":"xxx"}

2.获取POST参数

    // POST application/x-www-fORM-urlencoded
    r.POST("/login", func(c *gin.Context) {
        username := c.PostForm("username")
        pwd := c.PostForm("pwd")
        c.JSON(200, gin.H{
            "username": username,
            "pwd":      pwd,
        })
    })

获取结果

% curl -X POST "http://localhost:8080/login?username=aaa&pwd=bbb"
{"pwd":"","username":""}

3.Query和POST混合参数

    // ### 3.Query和POST混合参数
    r.POST("/any", func(c *gin.Context) {
        id := c.Query("id")
        username := c.PostForm("username")
        pwd := c.DefaultPostForm("pwd", "") // 默认空

        c.JSON(200, gin.H{
            "id":       id,
            "username": username,
            "password": pwd,
        })
    })

获取结果:

% curl -X POST "http://localhost:8080/any?id=1" -d "username=aaa&pwd=bbb"
{"id":"1","password":"bbb","username":"aaa"}% 

4.接收JSON参数

    // ### 4.接收JSON参数
    // 定义接收 User 的结构体
    type User struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }
    r.POST("/json", func(c *gin.Context) {
        var user User
        err := c.BindJSON(&user)
        if err != nil {
            c.JSON(200, gin.H{"code": 400, "msg": "error", "data": nil})
            return
        } else {
            c.JSON(200, gin.H{"code": 0, "msg": "success", "data": user})
        }
    })

获取结果:

# 正常请求
 % curl -H "Content-Type:application/json" -X POST --data '{"username":"aaa","password":"bbb"}' "http://localhost:8080/json"

{"code":0,"data":{"username":"aaa","password":"bbb"},"msg":"success"} 

# 错误请求
% curl -X POST "http://localhost:8080/json"

{"code":400,"data":null,"msg":"error"}  

路由重定向(Redirect)

    // 路由重定向
    r.GET("/goto", func(c *gin.Context) {
        c.Redirect(301, "/ping") // 301 永久重定向
    })

    // 获取路由内容
    r.GET("/index", func(c *gin.Context) {
        c.Request.URL.Path = "/ping"
        r.HandleContext(c)
    })

获取结果:

% curl "http://localhost:8080/index"
{"message":"pong"}                                                            % curl -i "http://localhost:8080/goto"
HTTP/1.1 301 Moved Permanently
Content-Type: text/html; charset=utf-8
Location: /ping
Date: Sun, 29 Nov 2020 11:00:20 GMT
Content-Length: 40

<a href="/ping">Moved Permanently</a>.

总结

Gin 框架的路由相对简单且优雅,所以只需要多加练习就可掌握它们的用法。

--结束END--

本文标题: 二、Gin 路由(Route)和获取请求参数的方法

本文链接: https://www.lsjlt.com/news/99277.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作