Go语言HTTP文件上传与下载教程
项目介绍
本项目是一个使用Go语言实现的基本HTTP文件上传和下载功能的示例。项目地址为:golang-http-file-upload-download。该项目展示了如何使用Go语言的标准库来处理文件上传和下载,适用于初学者学习和参考。
项目快速启动
环境准备
- 安装Go语言环境(版本1.13以上)。
- 克隆项目到本地:
git clone https://github.com/zupzup/golang-http-file-upload-download.git
运行项目
- 进入项目目录:
cd golang-http-file-upload-download
- 运行项目:
go run main.go
代码示例
以下是项目的主要代码片段,展示了如何设置文件上传和下载的路由:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
)
const maxUploadSize = 2 * 1024 * 1024 // 2 MB
var uploadPath = os.TempDir()
func main() {
http.HandleFunc("/upload", uploadFileHandler())
fs := http.FileServer(http.Dir(uploadPath))
http.Handle("/files/", http.StripPrefix("/files", fs))
log.Print("Server started on localhost:8080, use /upload for uploading files and /files/[fileName] for downloading")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func uploadFileHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
http.Error(w, "The uploaded file is too big. Please choose an file that's less than 2 MB in size", http.StatusBadRequest)
return
}
file, fileHeader, err := r.FormFile("uploadFile")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
fileName := filepath.Base(fileHeader.Filename)
dest, err := os.Create(filepath.Join(uploadPath, fileName))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dest.Close()
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := dest.Write(fileBytes); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Successfully uploaded file: %s", fileName)
})
}
应用案例和最佳实践
应用案例
本项目可以用于以下场景:
- 文件分享平台:用户可以上传文件并通过链接分享给其他人下载。
- 内部文件管理系统:企业内部使用,用于上传和下载文档。
最佳实践
- 文件大小限制:设置合理的文件大小限制,防止服务器资源被滥用。
- 文件类型检查:对上传的文件类型进行检查,确保只允许上传安全的文件类型。
- 安全性:确保上传和下载的路径安全,避免路径遍历攻击。
典型生态项目
本项目可以与其他Go语言生态项目结合使用,例如:
- Gin框架:使用Gin框架来构建更复杂的Web应用