Golang GinWeb框架2-文件上传/程序panic崩溃后自定义处理方式

开发 前端
本文接着上文(Golang GinWeb框架-快速入门/参数解析)继续探索GinWeb框架

[[353965]]

 简介

本文接着上文(Golang GinWeb框架-快速入门/参数解析)继续探索GinWeb框架

上传文件

单文件上传

注意: 文件名必须是安全可信赖的, 需要去掉路径信息,保留文件名即可

  1. package main 
  2.  
  3. import ( 
  4.   "fmt" 
  5.   "github.com/gin-gonic/gin" 
  6.   "log" 
  7.   "net/http" 
  8.   "os" 
  9.  
  10. func main() { 
  11.   router := gin.Default() 
  12.   // Set a lower memory limit for multipart forms (default is 32 MiB) 
  13.   // 设置请求表单最大内存限制,默认是30MB 
  14.  
  15.   //内部调用http请求的ParseMultipartForm方法,该方法要求传入一个字节数, 要取MultipartForm字段的数据,先使用ParseMultipartForm()方法解析Form,解析时会读取所有数据,但需要指定保存在内存中的最大字节数,剩余的字节数会保存在临时磁盘文件中 
  16.   maxMultipartMemory := int64(8 << 20) 
  17.   log.Printf("解析文件到内存的最大字节:%d", maxMultipartMemory) 
  18.   router.MaxMultipartMemory = maxMultipartMemory  // 8 MiB 
  19.   router.POST("/upload", func(c *gin.Context) { 
  20.     // single file 
  21.     file, _ := c.FormFile("file")  //FormFile从表单中返回第一个匹配到的文件对象(结构) 
  22.     log.Printf("获取到的文件名:%s", file.Filename)  //文件名必须是安全可信耐的,需要去掉路径信息,保留文件名即可 
  23.  
  24.     // Upload the file to specific dst. 
  25.     currentPath, _ := os.Getwd()  //获取当前文件路径 
  26.     dst := currentPath + "/" + file.Filename 
  27.     log.Printf("保存文件绝对路径:%s", dst) 
  28.     c.SaveUploadedFile(file, dst) 
  29.  
  30.     c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) 
  31.   }) 
  32.   router.Run(":8080"
  33.  
  34. //模拟单文件上传: 
  35. //curl -X POST http://localhost:8080/upload  -H "Content-Type: multipart/form-data" -F "file=@文件名" 

多文件上传, 详情参考(https://github.com/gin-gonic/examples/blob/master/upload-file/multiple/main.go)

  1. package main 
  2.  
  3. import ( 
  4.   "fmt" 
  5.   "github.com/gin-gonic/gin" 
  6.   "log" 
  7.   "net/http" 
  8.   "os" 
  9.  
  10. func main() { 
  11.   router := gin.Default() 
  12.   // Set a lower memory limit for multipart forms (default is 32 MiB) 
  13.   // 设置请求表单最大内存限制,默认是30MB 
  14.   //内部调用http请求的ParseMultipartForm方法,该方法要求传入一个字节数, 要取MultipartForm字段的数据,先使用ParseMultipartForm()方法解析Form,解析时会读取所有数据,但需要指定保存在内存中的最大字节数,剩余的字节数会保存在临时磁盘文件中 
  15.   maxMultipartMemory := int64(8 << 20) 
  16.   log.Printf("解析文件到内存的最大字节:%d", maxMultipartMemory) 
  17.   router.MaxMultipartMemory = maxMultipartMemory  // 8 MiB 
  18.   router.POST("/upload", func(c *gin.Context) { 
  19.     // Upload the file to specific dst. 
  20.     currentPath, _ := os.Getwd()  //获取当前文件路径 
  21.     // Multipart form 
  22.     form, _ := c.MultipartForm() //多文件表单 
  23.     files := form.File["upload[]"] //通过前端提供的键名获取文件数组 
  24.     for _, file := range files { 
  25.       dst := currentPath + "/" + file.Filename 
  26.       log.Printf("保存文件绝对路径:%s", dst) 
  27.       // Upload the file to specific dst. 
  28.       c.SaveUploadedFile(file, dst) 
  29.     } 
  30.     c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) 
  31.   }) 
  32.   router.Run(":8080"
  33.  
  34. //模拟多文件上传 
  35. //curl -X POST http://localhost:8080/upload -H "Content-Type: multipart/form-data" -F "upload[]=@文件1" -F "upload[]=@文件2" 

路由分组

路由分组可用于新老接口兼容, 针对不同分组的路由使用不同的中间件处理逻辑等

  1. func main() { 
  2.   router := gin.Default() 
  3.   // Simple group: v1  路由分组1 
  4.   v1 := router.Group("/v1"
  5.   { 
  6.     v1.POST("/login", loginEndpoint) 
  7.     v1.POST("/submit", submitEndpoint) 
  8.     v1.POST("/read", readEndpoint) 
  9.   } 
  10.   // Simple group: v2  路由分组2 
  11.   v2 := router.Group("/v2"
  12.   { 
  13.     v2.POST("/login", loginEndpoint) 
  14.     v2.POST("/submit", submitEndpoint) 
  15.     v2.POST("/read", readEndpoint) 
  16.   } 
  17.   router.Run(":8080"

中间件

我们可以用下面的两种方式初始化Gin引擎

  1. r := gin.New() //得到一个不使用任何中间件的Gin引擎Engine对象r 
  2.  
  3. // Default With the Logger and Recovery middleware already attached 
  4. // 默认方法使用Logger(日志记录器)和Recovery(异常自恢复)中间件 
  5. r := gin.Default() 

自定义程序崩溃后的处理方式(邮件,微信,短信等告警)

  1. package main 
  2.  
  3. import ( 
  4.   "fmt" 
  5.   "github.com/gin-gonic/gin" 
  6.   "log" 
  7.   "net/http" 
  8.  
  9. func CustomRecovery() gin.HandlerFunc { 
  10.   return func(c *gin.Context) { 
  11.     defer func() { 
  12.       //if r := recover(); r != nil { 
  13.       //  log.Printf("崩溃信息:%s", r) 
  14.       //} 
  15.  
  16.       if err, ok := recover().(string); ok { 
  17.         log.Printf("您可以在这里完成告警任务,邮件,微信等告警"
  18.         c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) 
  19.       } 
  20.       c.AbortWithStatus(http.StatusInternalServerError) 
  21.     }() 
  22.     c.Next() 
  23.   } 
  24.  
  25. func main() { 
  26.   // Creates a router without any middleware by default 
  27.   r := gin.New() 
  28.  
  29.   // Global middleware 
  30.   // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release. 
  31.   // By default gin.DefaultWriter = os.Stdout 
  32.   r.Use(gin.Logger()) 
  33.  
  34.   // Recovery middleware recovers from any panics and writes a 500 if there was one. 
  35.   //r.Use(CustomRecovery())  //使用自定义中间件处理程序崩溃 
  36.  
  37.   //使用匿名函数组成中间件,处理程序崩溃 
  38.   r.Use(func( c *gin.Context){ 
  39.     defer func() { 
  40.       if err, ok := recover().(string); ok { 
  41.         log.Printf("您可以在这里完成告警任务,邮件,微信等告警"
  42.         c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err)) 
  43.       } 
  44.       c.AbortWithStatus(http.StatusInternalServerError) 
  45.     }() 
  46.     c.Next() 
  47.   }) 
  48.  
  49.   r.GET("/panic", func(c *gin.Context) { 
  50.     // panic with a string -- the custom middleware could save this to a database or report it to the user 
  51.     panic("程序崩溃"
  52.   }) 
  53.  
  54.   r.GET("/", func(c *gin.Context) { 
  55.     c.String(http.StatusOK, "ohai"
  56.   }) 
  57.  
  58.   // Listen and serve on 0.0.0.0:8080 
  59.   r.Run(":8080"
  60. //模拟程序崩溃: curl http://localhost:8080/panic 

参考文档

Gin官方仓库:https://github.com/gin-gonic/gin

 

责任编辑:姜华 来源: 云原生云
相关推荐

2020-11-25 09:10:39

Golang GinW

2020-12-10 10:22:48

GinWeb中间件HTTPS

2020-12-08 12:05:48

Golang GinW框架HTTPS

2020-12-03 09:28:05

Golang GinW

2020-11-23 10:48:39

Golang GinW

2022-03-07 14:39:01

前端框架批处理

2021-05-28 08:58:41

Golang网卡metrics

2020-11-26 10:08:17

Golang GinW

2023-10-31 09:10:39

2020-12-02 11:18:28

Golang GinW

2023-07-28 09:26:43

GolangZap

2009-06-25 14:53:35

自定义UI组件JSF框架

2023-07-10 08:00:13

架构Rest返回值

2022-09-20 07:01:50

对象初始化代码

2021-01-14 19:04:36

框架数据库mybatis

2009-11-05 10:38:05

Visual Stud

2009-07-07 14:32:47

JDK日志Formatter

2009-12-31 14:25:19

Silverlight

2017-04-17 10:05:51

Hadoop错误方式

2009-08-04 09:56:46

C#事件处理自定义事件
点赞
收藏

51CTO技术栈公众号