自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Golang GinWeb框架2-文件上傳/程序panic崩潰后自定義處理方式

開發(fā) 前端
本文接著上文(Golang GinWeb框架-快速入門/參數(shù)解析)繼續(xù)探索GinWeb框架

[[353965]]

 簡(jiǎn)介

本文接著上文(Golang GinWeb框架-快速入門/參數(shù)解析)繼續(xù)探索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.   // 設(shè)置請(qǐng)求表單最大內(nèi)存限制,默認(rèn)是30MB 
  14.  
  15.   //內(nèi)部調(diào)用http請(qǐng)求的ParseMultipartForm方法,該方法要求傳入一個(gè)字節(jié)數(shù), 要取MultipartForm字段的數(shù)據(jù),先使用ParseMultipartForm()方法解析Form,解析時(shí)會(huì)讀取所有數(shù)據(jù),但需要指定保存在內(nèi)存中的最大字節(jié)數(shù),剩余的字節(jié)數(shù)會(huì)保存在臨時(shí)磁盤文件中 
  16.   maxMultipartMemory := int64(8 << 20) 
  17.   log.Printf("解析文件到內(nèi)存的最大字節(jié):%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從表單中返回第一個(gè)匹配到的文件對(duì)象(結(jié)構(gòu)) 
  22.     log.Printf("獲取到的文件名:%s", file.Filename)  //文件名必須是安全可信耐的,需要去掉路徑信息,保留文件名即可 
  23.  
  24.     // Upload the file to specific dst. 
  25.     currentPath, _ := os.Getwd()  //獲取當(dāng)前文件路徑 
  26.     dst := currentPath + "/" + file.Filename 
  27.     log.Printf("保存文件絕對(duì)路徑:%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.   // 設(shè)置請(qǐng)求表單最大內(nèi)存限制,默認(rèn)是30MB 
  14.   //內(nèi)部調(diào)用http請(qǐng)求的ParseMultipartForm方法,該方法要求傳入一個(gè)字節(jié)數(shù), 要取MultipartForm字段的數(shù)據(jù),先使用ParseMultipartForm()方法解析Form,解析時(shí)會(huì)讀取所有數(shù)據(jù),但需要指定保存在內(nèi)存中的最大字節(jié)數(shù),剩余的字節(jié)數(shù)會(huì)保存在臨時(shí)磁盤文件中 
  15.   maxMultipartMemory := int64(8 << 20) 
  16.   log.Printf("解析文件到內(nèi)存的最大字節(jié):%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()  //獲取當(dāng)前文件路徑 
  21.     // Multipart form 
  22.     form, _ := c.MultipartForm() //多文件表單 
  23.     files := form.File["upload[]"] //通過前端提供的鍵名獲取文件數(shù)組 
  24.     for _, file := range files { 
  25.       dst := currentPath + "/" + file.Filename 
  26.       log.Printf("保存文件絕對(duì)路徑:%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" 

路由分組

路由分組可用于新老接口兼容, 針對(duì)不同分組的路由使用不同的中間件處理邏輯等

  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() //得到一個(gè)不使用任何中間件的Gin引擎Engine對(duì)象r 
  2.  
  3. // Default With the Logger and Recovery middleware already attached 
  4. // 默認(rèn)方法使用Logger(日志記錄器)和Recovery(異常自恢復(fù))中間件 
  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("您可以在這里完成告警任務(wù),郵件,微信等告警"
  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.   //使用匿名函數(shù)組成中間件,處理程序崩潰 
  38.   r.Use(func( c *gin.Context){ 
  39.     defer func() { 
  40.       if err, ok := recover().(string); ok { 
  41.         log.Printf("您可以在這里完成告警任務(wù),郵件,微信等告警"
  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官方倉(cāng)庫(kù):https://github.com/gin-gonic/gin

 

責(zé)任編輯:姜華 來源: 云原生云
相關(guān)推薦

2020-11-25 09:10:39

Golang GinW

2020-12-10 10:22:48

GinWeb中間件HTTPS

2020-12-03 09:28:05

Golang GinW

2020-12-08 12:05:48

Golang GinW框架HTTPS

2020-11-23 10:48:39

Golang GinW

2022-03-07 14:39:01

前端框架批處理

2020-11-26 10:08:17

Golang GinW

2021-05-28 08:58:41

Golang網(wǎng)卡metrics

2020-12-02 11:18:28

Golang GinW

2023-07-10 08:00:13

架構(gòu)Rest返回值

2023-10-31 09:10:39

2009-06-25 14:53:35

自定義UI組件JSF框架

2023-07-28 09:26:43

GolangZap

2009-12-31 14:25:19

Silverlight

2017-04-17 10:05:51

Hadoop錯(cuò)誤方式

2022-09-20 07:01:50

對(duì)象初始化代碼

2021-01-14 19:04:36

框架數(shù)據(jù)庫(kù)mybatis

2009-08-04 09:56:46

C#事件處理自定義事件

2021-03-31 09:11:27

URLErrorHTTPError

2010-01-18 16:58:29

VB.NET Over
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)