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

1. 自定义 HTTP 配置

func main() {
	r := gin.Default()
	http.ListenAndServe(":8080", r)
}

或者

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()
}

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
}

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() }

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")
}

输出结果:

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

4. 自定义重定向

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

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

在浏览器中访问 [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")
})

如下使用 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"})
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值