FileServer文檔:https://godoc.org/net/http#FileServer
今天看到http的 Handle 方法,所以就像試試,就找到FileServer
FileServer:
1.www.xx.com/ 根路徑 直接使用
http.Handle("/", http.FileServer(http.Dir("/tmp")))
2.www.xx.com/c/ 帶有請求路徑的 需要添加函數
http.Handle("/c/", http.StripPrefix("/c/", http.FileServer(http.Dir("/tmp"))))
example:
package main import ( "io" "log" "net/http" ) func helloHandler(rw http.ResponseWriter, req *http.Request) { url := req.Method + " " + req.URL.Path if req.URL.RawQuery != "" { url += "?" + req.URL.RawQuery } log.Println(url) io.WriteString(rw, "hello world") } func main() { http.Handle("/hello", http.NotFoundHandler()) http.Handle("/dir",http.StripPrefix("/dir", http.FileServer(http.Dir("/usr/local/")))) err := http.ListenAndServe(":8080", nil) //err := http.ListenAndServe(":8080",http.FileServer(http.Dir("/usr/local/"))) if err != nil { log.Fatal("...") } }