一、方法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,與檔案服務器無關,可以先不用關注,用這種方式,就可以把任意檔案夾下的檔案路由出來了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20858.html
標籤:Go
下一篇:對流量 資料包中資料進行行為分析
