goweb原生实现HTTP文件上传功能

作者:

文章目录
  • Win10及以上系统默认已安装Curl,打开命令提示符输入 curl –help,若显示帮助信息则无需安装 ​​手动安装方法​​  官网下载:访问 curl官网 选择Windows版本curl for Windows 若需在 Windows XP 等旧系统使用,需选择更低版本(如 curl 7.56.1) 解压配置:将压缩包解压至指定目录(如 C:curl),右键“此电脑”→属性→高级系统设置→环境变量→Path中添加 %CURL_HOME%bin 验证安装:重启CMD输入 curl -V 显示版本号即成功 基础语法  curl [选项] [URL] URL:目标地址(如 https://example.com )。 选项:控制请求行为,常用选项包括: -X <方法>:指定HTTP方法(如 GET、POST、PUT)。 -H "头字段":添加请求头(如 -H "Content-Type: application/json")。 -d "数据":发送请求体(POST/PUT时常用)。 -o <文件名>:将输出保存到文件。 -v:显示详细请求/响应信息(调试用)。 常见场景示例 # 发送GET请求 curl https://api.example.com/data curl -H “Authorization: Bearer token” https://api.example.com/protected # 发送POST请求 curl -X POST -d “name=John&age=30” https://api.example.com/users curl -X POST -H “Content-Type: application/json” -d “{“name”:”John”}” https://api.example.com/users # 下载文件 curl -o output.zip https://example.com/file.zip # 上传文件 curl -F “file=@localfile.txt” https://example.com/upload
  • netstat(Network Statistics)是 Windows、Linux/Unix 系统内置的网络诊断工具,用于显示网络连接、路由表、接口统计等信息。
  • 目录
    • curl命令
    • Netstat 详解:网络连接统计工具
      • Netstat 核心功能
        • 基础语法

    在Go语言中,使用原生net/http包实现HTTP文件上传功能,主要依赖multipart/form-data编码解析和文件流处理。

    package main
    
    import (
    	"fmt"
    	"io"
    	"log"
    	"net/http"
    	"os"
    	"path/filepath"
    	"strings"
    )
    
    func main() {
    	_, err := os.Stat(".uploads")
    	if err == nil {
    
    	}
    	if os.IsNotExist(err) {
    		// 文件夹不存在,创建文件夹
    		err := os.MkdirAll(".uploads", 0755)
    		if err != nil {
    			fmt.Errorf("创建文件夹失败: %w", err)
    		}
    
    	}
    	// 其他错误
    	fmt.Errorf("检查文件夹时出错: %w", err)
    
    	http.HandleFunc("/upload", uploadHandler)
    
    
    	log.Fatalln(http.ListenAndServe(":80", nil))
    }
    
    // 支持多文件/大文件上传
    func uploadHandler(w http.ResponseWriter, r *http.Request) {
    	// 1. 安全校验
    	if r.Method != "POST" {
    		w.WriteHeader(http.StatusMethodNotAllowed)
    		return
    	}
    
    	// 2. 限制上传大小(10GB)
    	r.Body = http.MaxBytesReader(w, r.Body, 10<<30)
    
    	// 3. 多文件处理
    	if err := r.ParseMultipartForm(32 << 20); err != nil {
    		log.Printf("Upload failed: %v", err)
    		w.WriteHeader(http.StatusBadRequest)
    		return
    	}
    
    	// 4. 遍历处理文件
    	files := r.MultipartForm.File["files"]
    	fmt.Println(files)
    	for _, fileHeader := range files {
    		file, err := fileHeader.Open()
    		if err != nil {
    			http.Error(w, err.Error(), http.StatusInternalServerError)
    			return
    		}
    		defer file.Close()
    
    		// 5. 安全存储
    		safePath := filepath.Join("uploads", filepath.Base(fileHeader.Filename))
    		fmt.Println(filepath.Base(fileHeader.Filename))
    		if strings.Contains(safePath, "..") {
    			http.Error(w, "Invalid file path", http.StatusBadRequest)
    			return
    		}
    		fmt.Println(safePath)
    		dst, err := os.Create(safePath)
    		if err != nil {
    			http.Error(w, err.Error(), http.StatusInternalServerError)
    			return
    		}
    		defer dst.Close()
    
    		if _, err := io.Copy(dst, file); err != nil {
    			http.Error(w, err.Error(), http.StatusInternalServerError)
    			return
    		}
    	}
    
    	w.Write([]byte("Upload successful"))
    }
    

    使用curl 测试:

    D:
    
    echo "hello world,file test upload" >> file.txt
    
    curl -H "Content-Type: multipart/form-data" -F "files=@file.txt" http://localhost/upload
    

    Win10及以上系统默认已安装Curl,打开命令提示符输入 curl --help,若显示帮助信息则无需安装

    ​手动安装方法​​ 

    • 官网下载:访问 curl官网 选择Windows版本curl for Windows
    • 若需在 Windows XP 等旧系统使用,需选择更低版本(如 curl 7.56.1)
    • 解压配置:将压缩包解压至指定目录(如 C:curl),右键“此电脑”→属性→高级系统设置→环境变量→Path中添加 %CURL_HOME%bin
    • 验证安装:重启CMD输入 curl -V 显示版本号即成功

    基础语法 

    curl [选项] [URL]
    
    • URL:目标地址(如 https://example.com )。

    • 选项:控制请求行为,常用选项包括:

      • -X <方法>:指定HTTP方法(如 GETPOSTPUT)。
      • -H "头字段":添加请求头(如 -H "Content-Type: application/json")。
      • -d "数据":发送请求体(POST/PUT时常用)。
      • -o <文件名>:将输出保存到文件。
      • -v:显示详细请求/响应信息(调试用)。

    常见场景示例

    # 发送GET请求
    curl https://api.example.com/data  
    curl -H "Authorization: Bearer token" https://api.example.com/protected  
    
    # 发送POST请求
    curl -X POST -d "name=John&age=30" https://api.example.com/users 
    curl -X POST -H "Content-Type: application/json" -d "{"name":"John"}" https://api.example.com/users 
    
    # 下载文件
    curl -o output.zip  https://example.com/file.zip 
    # 上传文件 
    curl -F "file=@localfile.txt"  https://example.com/upload  
    

    netstat(Network Statistics)是 Windows、Linux/Unix 系统内置的网络诊断工具,用于显示网络连接、路由表、接口统计等信息。

    1. 显示活动网络连接(TCP/UDP)
    2. 查看监听端口(服务是否运行)
    3. 统计网络接口流量(发送/接收数据)
    4. 路由表信息(IP 路由路径)
    5. 协议统计(IPv4/IPv6 数据包分析)

    netstat [选项]
    参数 说明
    -a 显示所有连接和监听端口
    -n 以数字形式显示地址和端口(禁用域名解析)
    -o 显示进程 PID(可配合任务管理器查杀恶意程序)
    -p TCP 仅显示 TCP 协议连接
    -e 显示网络接口流量统计(收发字节数)
    -r 显示路由表(类似 route print)
    -s 按协议显示统计信息(TCP/UDP/ICMP/IP)
    netstat -ano #查看所有活动连接
    netstat -ano | findstr ":80"  #检查 80 端口占用情况(排查 Web 服务冲突)
    netstat -e 2  #监控实时网络流量(每 2 秒刷新)
    netstat -s -p tcp #统计TCP协议相关数据(如重传率、连接数),辅助诊断网络性能问题
    

    常见TCP状态说明​​:

    • ​LISTEN​​:服务端监听端口
    • ​ESTABLISHED​​:双向通信中
    • ​TIME_WAIT​​:连接关闭后的等待状态(正常现象)
    • ​SYN_SENT​​:客户端发起连接请求

     

    • 解读:本地 192.168.1.2 通过临时端口 54321,正与远程服务器 93.184.216.34 的 TCP 端口(443)进行双向通信中。

    到此这篇关于goweb原生实现HTTP文件上传功能的文章就介绍到这了,更多相关go web HTTP文件上传内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!​

    您可能感兴趣的文章:

    • Go语言使用net/http实现简单登录验证和文件上传功能
    •  Go 语言实现 HTTP 文件上传和下载
    • Golang实现http文件上传小功能的案例
    • Golang+Android基于HttpURLConnection实现的文件上传功能示例

    站内搜索