建立文件上傳 API 是許多涉及使用者提交文件、圖像或其他媒體文件的 Web 應用程式的常見要求。在本文中,我們將指導您使用 Go 和 Gin 框架建立安全且有效率的文件上傳 API。您將學習如何設定項目、處理傳入檔案並安全地儲存它們,確保您的應用程式能夠可靠地管理使用者上傳的內容。
先決條件
去1.21
設定項目
設定 Go 專案依賴項。
go mod init app go get github.com/gin-gonic/gin
專案結構
├─ main.go ├─ models │ └─ product.go └─ public └─ index.html
專案文件
產品.go
Product 是一個簡單的結構,用於在我們的檔案上傳 API 中測試檔案上傳。
package models type Product struct { Name string }
主機程式
此文件設定檔上傳 API。它將創建並設定最小的 Go Web 應用程式。
package main import ( "app/models" "io" "net/http" "os" "path/filepath" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" ) func main() { router := gin.Default() uploadPath := "./public/uploads" os.MkdirAll(uploadPath, os.ModePerm) router.Static("/uploads", uploadPath) router.StaticFile("/", "./public/index.html") router.POST("/submit", func(c *gin.Context) { var product models.Product if err := c.ShouldBindWith(&product, binding.FormMultipart); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, err.Error()) return } image, _ := c.FormFile("Image") filePath := filepath.Join(uploadPath, image.Filename) src, _ := image.Open() dst, _ := os.Create(filePath) io.Copy(dst, src) c.JSON(http.StatusOK, gin.H{"Name": product.Name, "Image": image.Filename}) }) router.Run() }
- 初始化 Gin 路由器並設定為上傳目錄和 index.html 提供靜態檔案服務。
- 確保 ./public/uploads 目錄存在用於儲存上傳的檔案。
- 在 /submit 定義一個 POST 路由來處理檔案上傳,將檔案儲存到伺服器,並傳回產品名稱和上傳的檔案名稱。
- 啟動 Gin 伺服器來監聽傳入的請求。
索引.html
此 HTML 表單專為使用者上傳產品名稱以及關聯的圖片檔案而設計。
<meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet"> <script> function submitForm() { let form = document.getElementById('form') let data = new FormData(form) fetch('submit', { method: 'POST', body: data }).then(res => { res.json().then(result => { let alert = document.getElementById('alert') alert.children[0].innerText = `Upload success!\nName: ${result.Name}\nImage: ${result.Image}` alert.children[1].src = `/uploads/${result.Image}` alert.classList.remove('d-none') form.reset() }) }) return false } </script> <div class="container"> <div class="row mt-3"> <form id="form" onsubmit="return submitForm()"> <div class="mb-3 col-12"> <label class="form-label" for="name">Name</label> <input id="name" name="Name" class="form-control form-control-sm" required> </div> <div class="mb-3 col-12"> <label class="form-label" for="image">Image</label> <input type="file" accept="image/*" id="image" name="Image" class="form-control form-control-sm" required> </div> </form> </div> <div class="col-12"> <button class="btn btn-sm btn-primary">Submit</button> </div> <div id="alert" class="alert alert-success mt-3 d-none"> <p></p> <img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172551064373054.jpg?x-oss-process=image/resize,p_40" class="lazy" id="img" style="max-width:90%" alt="在 Go 中建立文件上傳 API" > </div> </div>
以上是在 Go 中建立文件上傳 API的詳細內容。更多資訊請關注PHP中文網其他相關文章!

在Go編程中,有效管理錯誤的方法包括:1)使用錯誤值而非異常,2)採用錯誤包裝技術,3)定義自定義錯誤類型,4)復用錯誤值以提高性能,5)謹慎使用panic和recover,6)確保錯誤消息清晰且一致,7)記錄錯誤處理策略,8)將錯誤視為一等公民,9)使用錯誤通道處理異步錯誤。這些做法和模式有助於編寫更健壯、可維護和高效的代碼。

在Go中實現並發可以通過使用goroutines和channels來實現。 1)使用goroutines來並行執行任務,如示例中同時享受音樂和觀察朋友。 2)通過channels在goroutines之間安全傳遞數據,如生產者和消費者模式。 3)避免過度使用goroutines和死鎖,合理設計系統以優化並發程序。

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

go'serrorhandlingisexplicit,治療eRROSASRETRATERTHANEXCEPTIONS,與pythonandjava.1)go'sapphifeensuresererrawaresserrorawarenessbutcanleadtoverbosecode.2)pythonandjavauseexeexceptionseforforforforforcleanerCodebutmaymobisserrors.3)

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

go'serrorhandlingurturnserrorsasvalues,與Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

AnefactiveInterfaceingoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForabStractionToswaPimplementations withoutchangingCallingCode.3)

集中式錯誤處理在Go語言中可以提升代碼的可讀性和可維護性。其實現方式和優勢包括:1.將錯誤處理邏輯從業務邏輯中分離,簡化代碼。 2.通過集中處理錯誤,確保錯誤處理的一致性。 3.使用defer和recover來捕獲和處理panic,增強程序健壯性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。