31

Golang vs PHP 之文件服务器

 5 years ago
source link: https://studygolang.com/articles/13658?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前面的话

作者为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文件,丢到服务器机子上执行。

继续测试!结果: 成功,稳!


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK