go-upload

这个博客展示了如何使用Go语言构建一个简单的HTTP服务器,支持单文件上传和下载功能。用户可以通过网页选择文件进行上传,并能查看已上传的文件。在Ubuntu系统中运行时遇到权限问题,需要使用sudo启动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

go-upload
基于go原生http单文件上传下载web.

package main

import (
	"io"
	"net/http"
	"os"
)

var html = `
<html>
<body>
<form enctype="multipart/form-data" action="/" method="post">
  <input type="file" name="file" />
  <input type="submit" value="上传" />
</form>
<form enctype="multipart/form-data" action="/files/" method="get">
  <input type="submit" value="查看文件" />
</form>
</body>
</html>
`

func ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		switch r.Method {
		case "GET":
			w.Write([]byte(html))
		case "POST":
			r.ParseMultipartForm(32 << 20)
			file, header, _ := r.FormFile("file")
			defer file.Close()
			f, _ := os.OpenFile("./files/"+header.Filename, os.O_WRONLY|os.O_CREATE, 0666)
			defer f.Close()
			io.Copy(f, file)

			w.Write([]byte(html))
			io.WriteString(w, string(header.Filename+" 上传成功!"))
		}
	} else if r.URL.Path == "/files/" {
		had := http.StripPrefix("/files/", http.FileServer(http.Dir("files")))
		had.ServeHTTP(w, r)
		w.Write([]byte(html))
	}
}

func main() {
	_, err := os.Stat("files")
	if os.IsNotExist(err) {
		os.MkdirAll("files", 0777)
	}
	http.HandleFunc("/", ServeHTTP)
	http.ListenAndServe(":80", nil)
}

遇到一个问题。使用Ubuntu系统启动直接退出。
添加日志输出

	errs := http.ListenAndServe(":80", nil)
	fmt.Println(errs)
	
-- 启动输出
listen tcp :80: bind: permission denied

Ubuntu系统权限问题。使用sudo执行即可。sudo ./main

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值