Building a File Upload API in Go
Creating a file upload API is a common requirement for many web applications that involve users submitting documents, images, or other media files. In this article, we will guide you through building a secure and efficient file upload API using Go with the Gin framework. You’ll learn how to set up your project, handle incoming files, and store them securely, ensuring that your application can reliably manage user-uploaded content.
Prerequisites
Go 1.21
Setup project
Setting up the Go project dependencies.
go mod init app go get github.com/gin-gonic/gin
Project structure
├─ main.go ├─ models │ └─ product.go └─ public └─ index.html
Project files
product.go
The Product is a simple struct used for testing file uploads in our file upload API.
package models type Product struct { Name string }
main.go
This file sets up a file upload API. It will create and set up the minimal Go web application.
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() }
- Initializes a Gin router and sets up static file serving for the upload directory and index.html.
- Ensures the ./public/uploads directory exists for storing uploaded files.
- Defines a POST route at /submit to handle file uploads, save the file to the server, and return the product's name and uploaded file name.
- Starts the Gin server to listen for incoming requests.
index.html
This HTML form is designed for users to upload a product name along with an associated image file.
<!DOCTYPE html> <head> <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> </head> <body> <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> </div> <div class="col-12"> <button class="btn btn-sm btn-primary">Submit</button> </div> </form> <div id="alert" class="alert alert-success mt-3 d-none"> <p></p> <img id="img" width="200px" /> </div> </div> </div> </body> </html>
The form is set to submit via a JavaScript function, submitForm(), which is triggered on form submission. Additionally, there is a hidden alert section that can display the uploaded image and a success message after submission successfully.
Run project
go run main.go
Open the web browser and goto http://localhost:8080
You will find this test page.
Testing
Enter the name in the input field and browse for a file to upload.
Click the submit button to send the form. You will then see a success message along with the submitted information returned from our API.
In essence, Go with the Gin framework streamlines the management of file uploads in web applications. By using a straightforward handler and form setup, you can efficiently handle file uploads and improve the user experience in your projects.
Source code: https://github.com/stackpuz/Example-File-Upload-Go
Create a CRUD Web App in Minutes: https://stackpuz.com
The above is the detailed content of Building a File Upload API in Go. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
