【Go语言教学】相册文件服务器
Tofloor
poster avatar
海天鹰
deepin
2019-08-06 01:23
Author
功能:目录生成链接,其他文件生成图片。
已知问题:
1.http.HandleFunc 如何设置绝对路径?
2.outil.ReadDir 和图片无法打开含空格或者中文的路径。
3.速度慢。

package main

import (
        "net/http"
        "fmt"
        "io/ioutil"
        "strings"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
        fmt.Println(r.Proto + " " + r.Host + r.RequestURI);
        dir := "." + r.RequestURI;
        strings.Replace(dir, "%20", " ", -1);
        files, err := ioutil.ReadDir(dir);
        fmt.Println("genList(" + dir + ")");
        if err != nil {
                fmt.Println("Line 17: " + err.Error());
                http.ServeFile(w, r, "." + r.RequestURI);
        } else {
        str := "\n\n文件列表\n\n\n\n";
    for _, file := range files {
                rp := "";
                if (r.RequestURI != "/") {
                        rp = r.RequestURI;
                }
                if (file.IsDir()) {
                        str += "

" + file.Name() + "

\n";
                } else {
                        str += "\n";
                }
    }       
        str += "\n";
        w.Write([]byte(str));
        }
}

func main() {
        fmt.Println("http://localhost:8000");
        http.HandleFunc("/", handleRequest);
        http.ListenAndServe(":8000", nil);
}

Reply Favorite View the author
All Replies

No replies yet