iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么
  • 190
分享到

Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么

2024-04-02 19:04:59 190人浏览 八月长安
摘要

这篇文章主要讲解了“golang GinWEB框架之文件上传/程序panic崩溃后自定义处理方式是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Gola

这篇文章主要讲解了“golang GinWEB框架之文件上传/程序panic崩溃后自定义处理方式是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么”吧!

上传文件

单文件上传

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

package main  import (   "fmt"   "GitHub.com/gin-gonic/gin"   "log"   "net/Http"   "os" )  func main() {   router := gin.Default()   // Set a lower memory limit for multipart fORMs (default is 32 MiB)   // 设置请求表单最大内存限制,默认是30MB    //内部调用http请求的ParseMultipartForm方法,该方法要求传入一个字节数, 要取MultipartForm字段的数据,先使用ParseMultipartForm()方法解析Form,解析时会读取所有数据,但需要指定保存在内存中的最大字节数,剩余的字节数会保存在临时磁盘文件中   maxMultipartMemory := int64(8 << 20)   log.Printf("解析文件到内存的最大字节:%d", maxMultipartMemory)   router.MaxMultipartMemory = maxMultipartMemory  // 8 MiB   router.POST("/upload", func(c *gin.Context) {     // single file     file, _ := c.FormFile("file")  //FormFile从表单中返回第一个匹配到的文件对象(结构)     log.Printf("获取到的文件名:%s", file.Filename)  //文件名必须是安全可信耐的,需要去掉路径信息,保留文件名即可      // Upload the file to specific dst.     currentPath, _ := os.Getwd()  //获取当前文件路径     dst := currentPath + "/" + file.Filename     log.Printf("保存文件绝对路径:%s", dst)     c.SaveUploadedFile(file, dst)      c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))   })   router.Run(":8080") }  //模拟单文件上传: //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)

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

路由分组

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

func main() {   router := gin.Default()   // Simple group: v1  路由分组1   v1 := router.Group("/v1")   {     v1.POST("/login", loginEndpoint)     v1.POST("/submit", submitEndpoint)     v1.POST("/read", readEndpoint)   }   // Simple group: v2  路由分组2   v2 := router.Group("/v2")   {     v2.POST("/login", loginEndpoint)     v2.POST("/submit", submitEndpoint)     v2.POST("/read", readEndpoint)   }   router.Run(":8080") }

中间件

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

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

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

package main  import (   "fmt"   "github.com/gin-gonic/gin"   "log"   "net/http" )  func CustomRecovery() gin.HandlerFunc {   return func(c *gin.Context) {     defer func() {       //if r := recover(); r != nil {       //  log.Printf("崩溃信息:%s", r)       //}        if err, ok := recover().(string); ok {         log.Printf("您可以在这里完成告警任务,邮件,微信等告警")         c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))       }       c.AbortWithStatus(http.StatusInternalServerError)     }()     c.Next()   } }  func main() {   // Creates a router without any middleware by default   r := gin.New()    // Global middleware   // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.   // By default gin.DefaultWriter = os.Stdout   r.Use(gin.Logger())    // Recovery middleware recovers from any panics and writes a 500 if there was one.   //r.Use(CustomRecovery())  //使用自定义中间件处理程序崩溃    //使用匿名函数组成中间件,处理程序崩溃   r.Use(func( c *gin.Context){     defer func() {       if err, ok := recover().(string); ok {         log.Printf("您可以在这里完成告警任务,邮件,微信等告警")         c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))       }       c.AbortWithStatus(http.StatusInternalServerError)     }()     c.Next()   })    r.GET("/panic", func(c *gin.Context) {     // panic with a string -- the custom middleware could save this to a database or report it to the user     panic("程序崩溃")   })    r.GET("/", func(c *gin.Context) {     c.String(http.StatusOK, "ohai")   })    // Listen and serve on 0.0.0.0:8080   r.Run(":8080") } //模拟程序崩溃: curl http://localhost:8080/panic

感谢各位的阅读,以上就是“Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么”的内容了,经过本文的学习后,相信大家对Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程网,小编将为大家推送更多相关知识点的文章,欢迎关注!

您可能感兴趣的文档:

--结束END--

本文标题: Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么

本文链接: https://www.lsjlt.com/news/84286.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么
    这篇文章主要讲解了“Golang GinWeb框架之文件上传/程序panic崩溃后自定义处理方式是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Gola...
    99+
    2024-04-02
  • pycharm中venv文件夹自定义处理方式是什么
    本篇内容介绍了“pycharm中venv文件夹自定义处理方式是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!pycharm每次新建项目都...
    99+
    2023-06-30
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作