golang文件服務器,可以訪問任何目錄


一、方法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,與文件服務器無關,可以先不用關注。用這種方式,就可以把任意文件夾下的文件路由出來了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM