python3 -m http.server
非常适合托管文件,但有时我在没有安装python的用户(Windows用户)在场的情况下,需要从他们那里获取文件。怎么办?
答案 0 :(得分:-1)
<code>
package main
import (
"net/http"
"io"
"os"
"log"
"regexp"
)
//curl http://192.168.1.100/getip
//curl -o abc http://192.168.1.100/download?file=abc
//curl -F "file=@abc" http://192.168.1.100/upload
const BaseUploadPath = "/repo/upload"
const BaseDownloadPath = "/repo/download"
func main() {
http.HandleFunc("/upload", handleUpload)
http.HandleFunc("/download", handleDownload)
http.HandleFunc("/getip", handleGetip)
err := http.ListenAndServe(":80", nil)
if err != nil {
log.Fatal("Server run fail")
}
}
func handleGetip(w http.ResponseWriter, request *http.Request){
r := regexp.MustCompile(`\d+.\d+.\d+.\d+`)
ipaddr := r.FindString(request.RemoteAddr)
_,_ = io.WriteString(w, ipaddr)
}
func handleUpload (w http.ResponseWriter, request *http.Request) {
file, fileHeader, err := request.FormFile("file")
if err != nil {
_, _ = io.WriteString(w, "Read file error")
return
}
defer file.Close()
log.Println("filename: " + fileHeader.Filename)
newFile, err := os.Create(BaseUploadPath + "/" + fileHeader.Filename)
if err != nil {
_, _ = io.WriteString(w, "Create file error")
return
}
defer newFile.Close()
_, err = io.Copy(newFile, file)
if err != nil {
_, _ = io.WriteString(w, "Write file error")
return
}
_,_ = io.WriteString(w, "Upload success")
}
func handleDownload (w http.ResponseWriter, request *http.Request) {
filename := request.FormValue("filename")
if filename == "" {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
log.Println("filename: " + filename)
file, err := os.Open(BaseDownloadPath + "/" + filename)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
defer file.Close()
w.Header().Add("Content-type", "application/octet-stream")
w.Header().Add("content-disposition", "attachment; filename=\""+filename+"\"")
_, err = io.Copy(w, file)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, "Bad request")
return
}
}
</code>