Go语言实现文件下载功能:后端代码示例
以下是一份可能的代码实现:
package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
// 获取文件路径
filePath := r.URL.Query().Get("file")
if filePath == "" {
http.Error(w, "Missing file parameter", http.StatusBadRequest)
return
}
// 打开文件
file, err := os.Open(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
// 设置响应头
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename='%s'", filePath))
// 下载文件
_, err = io.Copy(w, file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
http.ListenAndServe(":8080", nil)
}
这个程序通过 http.HandleFunc 注册了一个 /download 的路由,当接收到 GET 请求时,会从 Query 参数中获取 file 参数,然后以附件形式下载指定路径的文件。同时,程序设置了 Content-Type 和 Content-Disposition 响应头,以便浏览器知道该如何处理返回的数据。
这个程序可以在命令行中运行,也可以打包成 Docker 镜像等形式部署到服务器上。如果需要在其他地方调用这个程序,可以通过 HTTP 请求访问 /download 路由,并传递 file 参数即可。
原文地址: https://www.cveoy.top/t/topic/mv38 著作权归作者所有。请勿转载和采集!