歡迎您光臨本站 註冊首頁

golang文件服務器的兩種方式(可以訪問任何目錄)

←手機掃碼閱讀     lousu-xi @ 2020-05-04 , reply:0

一、方法1:
主要用到的方法是http包的FileServer,參數很簡單,就是要路由的文件夾的路徑。
package main import ( "fmt" "net/http" ) func main() { http.Handle("/", http.FileServer(http.Dir("./"))) e := http.ListenAndServe(":8080", nil) fmt.Println(e) }
上面例子的路由只能把根目錄也就是“/”目錄映射出來,例如你寫成”http.Handle("/files", http.FileServer(http.Dir("./")))“,就無法把通過訪問”/files“把當前路徑下的文件映射出來。於是就有了http包的StripPrefix方法。
二、方法2:
實現訪問任意文件夾下面的文件。
package main import ( "fmt" "net/http" ) func main() { mux := http.NewServeMux() mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("/")))) mux.Handle("/c/", http.StripPrefix("/c/", http.FileServer(http.Dir("c:")))) mux.Handle("/d/", http.StripPrefix("/d/", http.FileServer(http.Dir("d:")))) mux.Handle("/e/", http.StripPrefix("/e/", http.FileServer(http.Dir("e:")))) if err := http.ListenAndServe(":3008", mux); err != nil { log.Fatal(err) } }
這裡生成了一個ServeMux,與文件服務器無關,可以先不用關注。用這種方式,就可以把任意文件夾下的文件路由出來了。
ps:golang實現的文件服務器
最近在學習golang,使用golang實現了一個最簡單的文件服務器,程序只有簡單的十多行代碼,可以編譯成windows, linux, mac多平臺可執行文件。
源碼
package main import ( "fmt" "net/http" "os" "path/filepath" ) func main() { p, _ := filepath.Abs(filepath.Dir(os.Args[0])) http.Handle("/", http.FileServer(http.Dir(p))) err := http.ListenAndServe(":8088", nil) if err != nil { fmt.Println(err) } }
源碼解釋
os.Args[0]獲取的是執行程序時的第一個參數,默認第一個參數是程序所在的目錄
filepath.Abs(filepath.Dir(os.Args[0]))是獲取當前可執行程序所在的絕對路徑
http.Handle("/", http.FileServer(http.Dir(p)))是開啟一個文件服務器,使用當前可執行文件所在的路徑
http.ListenAndServe(":8088", nil)是監聽8088端口並開啟文件服務器
編譯
要將源碼編譯成不同平臺的可執行文件,需要使用gox工具,使用下面的命令安裝gox:
go get github.com/mitchellh/gox
執行成功之後,使用gox命令即可自動編譯出各個平臺的可執行文件,如果想為某個平臺單獨編譯,可以使用如下方式:
gox -os "windows linux" -arch amd64
-os參數指定了編譯平臺,-arch參數指定了處理器架構
運行
直接打開編譯出來的可執行程序,即可運行,在瀏覽器中訪問http://ip:8088即可看到可執行文件所在的目錄下的所有文件。


[lousu-xi ] golang文件服務器的兩種方式(可以訪問任何目錄)已經有243次圍觀

http://coctec.com/docs/program/show-post-232875.html