• 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
  • 相关阅读:
    【QT】使用toBase64方法将.txt文件的明文变为非明文(类似加密)
    Spring——三级缓存
    深度学习——嵌入矩阵and学习词嵌入andWord2Vec
    算法总结10 线段树
    从Element日期组件源码中学到的两个工具方法
    大数据-之LibrA数据库系统告警处理(ALM-12034 周期备份任务失败)
    <能力清单>笔记与思考
    添加路由的2种方式--router
    计算机毕业设计(附源码)python在线答题系统
    《痞子衡嵌入式半月刊》 第 89 期
  • 原文地址:https://blog.csdn.net/wohu1104/article/details/126689046