1. 程式人生 > >基於gin的golang web開發:路由二

基於gin的golang web開發:路由二

在[基於gin的golang web開發:路由][1]中我們介紹了Gin的路由和一些獲取連結中引數的方法,本文繼續介紹其他獲取引數的方法。 #### 檔案上傳 在web開發中檔案上傳是一個很常見的需求,下面我們來看一下基於Gin的檔案上傳。 ```golang func main() { router := gin.Default() router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { file, _ := c.FormFile("file") log.Println(file.Filename) c.SaveUploadedFile(file, dst) c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename)) }) router.POST("/multiple_upload", func(c *gin.Context) { form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { log.Println(file.Filename) c.SaveUploadedFile(file, dst) } c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) }) router.Run(":8080") } ``` router.MaxMultipartMemory用於限制上傳檔案的大小,預設大小為32MiB。這個值可以根據你的業務設定具體的值,儘量不要設定的太大。 在本例中可以看到單檔案上傳和多檔案上傳的處理方式是不一樣的。 單檔案上傳時使用file, \_ := c.FormFile("file")獲取客戶端傳過來的檔案。這裡使用 \_ 忽略了錯誤,在生產環境你可能需要處理一下錯誤。file.Filename可以獲取到檔名。注意:file.Filename是一個可選的引數,不要使用這個引數儲存檔案,儲存檔案時最好自己生成一個新的檔名。 c.SaveUploadedFile儲存檔案到檔案系統,第一個引數傳入獲取到的檔案,第二個引數輸入檔案路徑。由於Go語言跨平臺的特性,在傳入檔案路徑引數的時候你可能要考慮到生產環境伺服器的作業系統。例如windows作業系統的檔案路徑可能是"c:\uploadfiles\1.png",linux作業系統的檔案路徑可能是"/var/uploadfiles/1.png"。 多檔案上傳時先獲取到表單form, \_ := c.MultipartForm(),然後獲取到檔案陣列files := form.File["upload[]"],最後迴圈操作檔案陣列中的每個檔案。 在本例中直接儲存檔案到檔案系統了,業務系統中可能會把上傳的檔案儲存到阿里雲的OSS或者七牛雲等檔案系統,替換c.SaveUploadedFile為不同檔案系統儲存檔案的方法就可以了。 #### 對映引數為Map 檔案引數是陣列的時候,Gin可以把引數對映為Map型別。 ```golang func main() { router := gin.Default() router.POST("/post", func(c *gin.Context) { ids := c.QueryMap("ids") names := c.PostFormMap("names") fmt.Printf("ids: %v; names: %v", ids, names) }) router.Run(":8080") } ``` c.QueryMap可以獲取到查詢字串中的陣列,c.PostFormMap可以獲取到表單引數中的陣列。向/post?ids[a]=1234&ids[b]=hello post提交資料 names[first]=thinkerou&names[second]=tianou,會看到輸出ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]。 還有另外一種處理陣列引數的方法。路徑是這樣的/post?ids=1234,hello,這種情況可以用[基於gin的golang web開發:路由][1]中提到的獲取查詢字串的方法:DefaultQuery或者Query,然後分割字串。 文章出處:[基於gin的golang web開發:路由二][2] [1]: https://www.huaface.com/article/12 [2]: https://www.huaface.com/arti