重定向
重定向到外部
使用Redirect()方法,http.StatusMovedPermanently表示http状态吗 301
1 2 3 4 5
|
r.GET("/redirect/baidu", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently,"https://www.baidu.com") })
|
重定向到内部路由
1 2 3 4 5 6
| r.GET("/luyou", func(c *gin.Context) { c.Request.URL.Path = "/router/info" r.HandleContext(c) })
|
上传单个文件
上传单个文件并存在当前目录下upload。使用FormFile 接收前端的文件,后端使用SaveUploadedFile保存到本地。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| r.POST("/upload", func(c *gin.Context) { file,err := c.FormFile("file")
if err != nil { c.JSON(http.StatusInternalServerError,gin.H{ "message":err.Error(), }) return }
log.Print(file.Filename) dst := fmt.Sprintf("./upload/%s",file.Filename) c.SaveUploadedFile(file,dst) c.JSON(http.StatusOK,gin.H{ "message":fmt.Sprintf("'%s' uploaded!",file.Filename), })
})
|
html
1 2 3 4 5 6 7 8 9 10 11 12 13
| {{ template "base"}}
{{ define "content"}} <h1> server page {{ .username }} {{ .password}} </h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"><br> <input type="submit" value="上传"> </form> {{end}}
|
上传多个文件
路由
Gin路由系统用于接收用户请求,并将请求分发到中间件或请求处理器来进行处理。
常见的请求方法:
1 2 3 4 5 6
| router.GET() router.PATCH() router.POST() router.DELETE() router.PUT() router.ANY()
|
创建默认路由引擎
参考实例
1 2 3 4 5 6 7
| r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run()
|
路由组
使用Group方法定义一个路由组,由组来定义组下面的路由请求。请求方式如/router/info,/router/news 就会匹配到该路由组中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| NewRouter := r.Group("/router") { NewRouter.GET("info", func(c *gin.Context) { c.JSON(http.StatusOK,gin.H{ "path":"info", }) }) NewRouter.GET("news", func(c *gin.Context) { c.JSON(http.StatusOK,gin.H{ "path":"news", }) }) }
|
嵌套路由组比如/router/users/list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| NewRouter := r.Group("/router") { NewRouter.GET("info", func(c *gin.Context) { c.JSON(http.StatusOK,gin.H{ "path":"info", }) }) NewRouter.GET("news", func(c *gin.Context) { c.JSON(http.StatusOK,gin.H{ "path":"news", }) }) UserRouter := r.Group("user")
UserRouter.GET("list", func(c *gin.Context) { c.JSON(http.StatusOK,gin.H{ "path":"list", }) }) }
|
404路由
使用NoRoute识别404 URL
1 2 3 4 5 6
| r.NoRoute(func(c *gin.Context) { c.JSON(http.StatusOK,gin.H{ "status":"404", }) })
|