Uploading files in web applications is a common task, and Go makes it remarkably straightforward, especially when dealing with multipart/form-data. In this article, we'll cover how to handle file uploads using multipart requests in Go.
Setting Up Your Go Project
Begin by creating a new directory for your Go project. You can name it fileupload or any name of your choice.
Inside this directory, initialize your Go module:
go mod init fileuploadCreating the HTML Form
To facilitate file uploads, you need an HTML form that allows users to select files. Create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload File</title>
</head>
<body>
<h1>Upload a File</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="uploadfile"/>
<br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
Handling File Uploads in Go
Create a main.go file where we will implement the logic for handling HTTP requests and file uploads:
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func uploadFile(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Fprintf(w, "Error retrieving the file: %v", err)
return
}
defer file.Close()
f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Fprintf(w, "Error saving the file: %v", err)
return
}
defer f.Close()
io.Copy(f, file)
fmt.Fprintf(w, "File uploaded successfully: %v", handler.Filename)
}
func main() {
http.HandleFunc("/upload", uploadFile)
fmt.Println("Starting server at :8080")
http.ListenAndServe(":8080", nil)
}
This Go program sets up a server listening on port 8080 and expects file uploads at the /upload endpoint. The uploadFile function checks the request method, extracts the file from the request, and then writes it to the server's disk with the original filename.
Running Your File Upload Service
Now, it's time to test your file upload functionality:
go run main.goVisit http://localhost:8080 in your browser, choose a file for upload, and then submit the form. If everything is set up correctly, you'll see a message indicating a successful file upload, and you'll find the uploaded file in your project directory.
Conclusion
With Go's net/http package, handling file uploads with multipart requests is a clean and straightforward process. This simple application efficiently receives a file from a client and stores it on the server, easily expandable into more complex applications with additional file handling logic.