前面的話
作者為golang腦殘粉,本篇內容可能會引起phper不適,請慎讀!
前兩天有同事遇到一個問題,需要一個能支持上傳、下載功能的HTTP服務器做一個數據中心。我剛好弄過,於是答應幫他搭一個。
HTTP服務器,首先想到的就是PHP + nginx。於是開擼,先寫一個PHP的上傳
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "錯誤:: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " 文件已經存在。 ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "文件存儲在: " . "upload/" . $_FILES["file"]["name"];
}
}
?>
好了,寫好了!需求完成了!測試一下把!
於是開始第一次測試,結果:失敗!
原因是PHP的upload_max_filesize只有2M,上傳的文件大小超過限制了。
修改了一下php.ini配置,再次測試可以上傳了
那么部署到服務器上去把。服務器上有一個openresty(nginx的系列的web服務器),把upload.php文件丟里面,然后重啟服務。好了,又可以測試一下了!
於是第二次測試,結果:失敗!
原因是,openresty默認沒開php解析,要改下配置。把nginx.conf里的php解析打開一下。重啟nginx,然后再測試一下吧~
於是,第三次測試,還是失敗!
原來。。這台機器上,雖然有nginx,但是沒有安裝PHP!!! 想到還要去外網下載PHP,然后還要選版本,然后回來安裝還要配置環境變量以及openresty關聯php的配置后。。
算了,再見吧 PHP!
輪到Go語言上場的時候了!!
在golang的世界里1行代碼就能搞定一個文件服務器
package main
import (
"log"
"net/http"
)
func main() {
log.Fatal(http.ListenAndServe(":8038", http.FileServer(http.Dir("./"))))
}
就這樣,你就可以在本機訪問8038端口去下載指定路徑的文件了!不需要依賴nginx或者其他任何web服務器
包含上傳、下載功能的FileServer.go全部代碼如下
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
const (
uploadPath = "./Files/"
)
func main() {
http.HandleFunc("/upload", uploadHandle)
fs := http.FileServer(http.Dir(uploadPath))
http.Handle("/Files/", http.StripPrefix("/Files", fs))
log.Fatal(http.ListenAndServe(":8037", nil))
}
func uploadHandle(w http.ResponseWriter, r *http.Request) {
file, head, err := r.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
filePath := uploadPath + head.Filename
fW, err := os.Create(filePath)
if err != nil {
fmt.Println("文件創建失敗")
return
}
defer fW.Close()
_, err = io.Copy(fW, file)
if err != nil {
fmt.Println("文件保存失敗")
return
}
io.WriteString(w, "save to "+filePath)
}
如何部署
go是靜態編譯型語言,直接編譯出可執行文件,在windows上也就是exe。放到任何一台機器上,不需要安裝額外環境,就能直接運行!
所以編譯出FileServer.exe文件,丟到服務器機子上執行。