Go语言创建web server非常简单,部署也很容易,不像IIS、Apache等那么重量级,需要各种依赖、配置。一些功能单一的web 服务,用Go语言开发特别适合。http文件上传下载服务,在很多地方都能用到,大到门户网站,小到公司内部文件共享等。

下面的代码在后台上传处理代码里,先判断“key”字段,如果key 值与设定的“密码”不符合,则不保存文件,达到文件上传权限验证的目的。

注意在go程序运行目录里,创建一个“html”文件夹。

****************************main.go********************************

package main

import(

"fmt"

"io"

"net/http"

"os"

"strings"

)

func Upload(whttp.ResponseWriter,r*http.Request){

r.ParseMultipartForm(32<<20)

key:=strings.Join(r.Form["key"],"")

if key!="89437589"{

fmt.Fprintf(w,"authfailed")

return

}

file,handler,_:=r.FormFile("file")

defer file.Close()

f,_:=os.OpenFile("html/"+handler.Filename,os.O_WRONLY|os.O_CREATE,0666)

defer f.Close()

io.Copy(f,file)

fmt.Fprintf(w,"success")

}

func main(){

http.Handle("/",http.FileServer(http.Dir("html")))

http.HandleFunc("/upload",Upload)

http.ListenAndServe("0.0.0.0:8080",nil)

}

*****************************test.htm*******************************

<htmlxmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Upload Test</title>

</head>

<body>

<form enctype="multipart/form-data"action="/upload" method="POST">

UploadKey:<input type="text" value="89437589"name="key" />

UploadFile: <input type="file" name="file" />

<input type="submit" value="Upload" />

</form>

</body>

</html>

************************************************************

如果 UploadKey 的 value修改为非“89437589”,上传返回“authfailed”,表示上传验证失败。

可以根据实际情况,添加需要的验证、数据字段,比如user、subdir等。