Go语言HTTP文件上传与下载教程

Go语言HTTP文件上传与下载教程

golang-http-file-upload-downloadA simple example of an HTTP upload and download in Go项目地址:https://gitcode.com/gh_mirrors/go/golang-http-file-upload-download

项目介绍

本项目是一个使用Go语言实现的基本HTTP文件上传和下载功能的示例。项目地址为:golang-http-file-upload-download。该项目展示了如何使用Go语言的标准库来处理文件上传和下载,适用于初学者学习和参考。

项目快速启动

环境准备

  1. 安装Go语言环境(版本1.13以上)。
  2. 克隆项目到本地:
    git clone https://github.com/zupzup/golang-http-file-upload-download.git
    

运行项目

  1. 进入项目目录:
    cd golang-http-file-upload-download
    
  2. 运行项目:
    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)
    })
}

应用案例和最佳实践

应用案例

本项目可以用于以下场景:

  1. 文件分享平台:用户可以上传文件并通过链接分享给其他人下载。
  2. 内部文件管理系统:企业内部使用,用于上传和下载文档。

最佳实践

  1. 文件大小限制:设置合理的文件大小限制,防止服务器资源被滥用。
  2. 文件类型检查:对上传的文件类型进行检查,确保只允许上传安全的文件类型。
  3. 安全性:确保上传和下载的路径安全,避免路径遍历攻击。

典型生态项目

本项目可以与其他Go语言生态项目结合使用,例如:

  1. Gin框架:使用Gin框架来构建更复杂的Web应用

golang-http-file-upload-downloadA simple example of an HTTP upload and download in Go项目地址:https://gitcode.com/gh_mirrors/go/golang-http-file-upload-download

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水珊习Gale

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值