• Gin 笔记(04)— 自定义 HTTP 配置、使用 HTTP 方法、自定义请求 url 不存在时的返回值、自定义重定向


    1. 自定义 HTTP 配置

    func main() {
    	r := gin.Default()
    	http.ListenAndServe(":8080", r)
    }
    
    • 1
    • 2
    • 3
    • 4

    或者

    func main() {
    	r := gin.Default()
    
    	s := &http.Server{
    		Addr:           ":8080",
    		Handler:        r,
    		ReadTimeout:    10 * time.Second,
    		WriteTimeout:   10 * time.Second,
    		MaxHeaderBytes: 1 << 20,
    	}
    	s.ListenAndServe()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2. 使用 HTTP 方法

    HTTP 协议支持的方法 GETHEADPOSTPUTDELETEOPTIONSTRACEPATCHCONNECT 等都在 Gin 框架中都得到了支持。

    func main() {
    	// Creates a gin router with default middleware:
    	// logger and recovery (crash-free) middleware
    	router := gin.Default()
    
    	router.GET("/someGet", getting)
    	router.POST("/somePost", posting)
    	router.PUT("/somePut", putting)
    	router.DELETE("/someDelete", deleting)
    	router.PATCH("/somePatch", patching)
    	router.HEAD("/someHead", head)
    	router.OPTIONS("/someOptions", options)
    
    	// By default it serves on :8080 unless a
    	// PORT environment variable was defined.
    	router.Run()
    	// router.Run(":3000") for a hard coded port
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    Gin 中特别定义了一个 Any() 方法,在 routergroup.go 文件中可看到具体定义 ,它能匹配以上 9 个 HTTP 方法,具体定义如下:

       func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {group.handle("GET", relativePath, handlers)
            group.handle("POST", relativePath, handlers)
            group.handle("PUT", relativePath, handlers)
            group.handle("PATCH", relativePath, handlers)
            group.handle("HEAD", relativePath, handlers)
            group.handle("OPTIONS", relativePath, handlers)
            group.handle("DELETE", relativePath, handlers)
            group.handle("CONNECT", relativePath, handlers)
            group.handle("TRACE", relativePath, handlers)
            return group.returnObj() }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    HTTP 支持的方法 —GET、POST 和 PUT 区别

    3. 自定义请求 url 不存在时的返回值

    // NoResponse 请求的 url 不存在,返回 404
    func NoResponse(c *gin.Context) {
        // 返回 404 状态码
        c.String(http.StatusNotFound, "404, page not exists!")
    }
    
    func main() {
        router := gin.Default()
        // 设定请求 url 不存在的返回值
        router.NoRoute(NoResponse)
    
        router.Run(":8080")
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    输出结果:

    $ curl  http://127.0.0.1:8080/bar
    404, page not exists!
    
    • 1
    • 2

    4. 自定义重定向

    生成 HTTP 重定向很方便,内部重定向和外部重定向都支持。

    r.GET("/test", func(c *gin.Context) {
    	c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
    })
    
    • 1
    • 2
    • 3

    在浏览器中访问 [http://127.0.0.1:8080/test](http://127.0.0.1:8080/test)会跳转到 www.baidu.com页面。

    要从 POST 方法重定向,可以参考: Redirect from POST ends in 404

    r.POST("/test", func(c *gin.Context) {
    	c.Redirect(http.StatusFound, "/foo")
    })
    
    • 1
    • 2
    • 3

    如下使用 HandleContext,可用于路由重定向

    r.GET("/test", func(c *gin.Context) {
        c.Request.URL.Path = "/test2"
        r.HandleContext(c)
    })
    
    r.GET("/test2", func(c *gin.Context) {
        c.JSON(200, gin.H{"hello": "world"})
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
  • 相关阅读:
    WebSocket的简单应用
    LeetCode 接雨水 双指针
    LeetCode_逆向思维_中等_453.最小操作次数使数组元素相等
    docker搭建的jenkins,jmeter和ant环境变量环配置
    (附源码)springboot炼糖厂地磅全自动控制系统 毕业设计 341357
    解决node_modules\node-sassnpm ERR! command failed
    Android项目启动处于loading状态, 无法正常加载目录结构
    Another app is currently holding the yum lock; waiting for it to exit
    Jenkins详细配置
    探索 Flutter 中的动画:使用 flutter_animate
  • 原文地址:https://blog.csdn.net/wohu1104/article/details/126689046