ファイル アップロード API の作成は、ユーザーがドキュメント、画像、またはその他のメディア ファイルを送信する多くの Web アプリケーションにとって共通の要件です。この記事では、Gin フレームワークで Go を使用して、安全で効率的なファイル アップロード API を構築する方法を説明します。プロジェクトを設定し、受信ファイルを処理し、それらを安全に保存して、ユーザーがアップロードしたコンテンツをアプリケーションで確実に管理できるようにする方法を学びます。
前提条件
Go 1.21
プロジェクトのセットアップ
Go プロジェクトの依存関係を設定します。
go mod init app go get github.com/gin-gonic/gin
プロジェクトの構造
├─ main.go ├─ models │ └─ product.go └─ public └─ index.html
プロジェクトファイル
製品.go
プロダクトは、ファイル アップロード 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 中国語 Web サイトの他の関連記事を参照してください。

fatestinggocodewithinit functions、useexplicitsetupfunctionsurseSorseparatet fileStoavoidepencyonInitonitisideEffects.1)useexplicitsetupfuncontrollglobalbariaveInitialization.2)createSeparateSteSteSteStobypassInit funtedtententen

Go'serrorhandlingReturnserrorsasasvalues、javaandpython whichuseexceptions.1)go'smethodensuresexpliciterror handling

効果的なインターフェイスリングミニマル、クリア、およびプロモテスルーシューリング。1)インターフェイスForfforfibilityOfimplementation.2)interfacesforact forabstractiontoswapimplementations withingingcallingcode.3)設計の快適性を発信すること

集中型エラー処理は、GO言語でのコードの読みやすさと保守性を向上させることができます。その実装方法と利点には、次のものが含まれます。1。ビジネスロジックからロジックを個別に処理し、コードを簡素化します。 2。中央の取り扱いによるエラー処理の一貫性を確保します。 3. DeferとRecoverを使用してパニックをキャプチャおよび処理して、プログラムの堅牢性を高めます。

Ingo、AlternativestoinititionCustomInitializationAndSingletons.1)CustomInitializationAltionsionAlowoveroveroveroveroveroveroveroveroveroveroveroveroveroveroveroverover curs、beantefordedorcontionalsetups.2)singletonsensureone-initializatializatializatialent

gohandlesinterfacesandtypeassertionseffectivivivivivity、強化された柔軟性と耐毒性を強化します

言語エラー処理は、エラーとエラーを介してより柔軟になり、読みやすくなります。 1.エラーは、エラーが指定されたエラーと同じであり、エラーチェーンの処理に適しているかどうかを確認するために使用されます。 2.エラー。エラータイプを確認するだけでなく、エラーを特定のタイプに変換することもできます。これは、エラー情報を抽出するのに便利です。これらの関数を使用すると、エラー処理ロジックを簡素化できますが、エラーチェーンの正しい配信に注意を払い、コードの複雑さを防ぐために過度の依存性を回避できます。

tomakegogoapplicationsRunfasterAndMore -efficient、useprofilingtools、leverageconconcurrency、andmanagememoryefcectively.1)useprofforcpuandmemoryprofilingtoidentififybottlenecks.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 中国語版
中国語版、とても使いやすい

WebStorm Mac版
便利なJavaScript開発ツール

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

ホットトピック









