使用中的问题之一
http.FileServer是请求路径用于构建文件名,因此,如果要从根目录以外的任何地方提供服务,则需要剥离到该处理程序的路由前缀。
标准库为此提供了一个有用的工具
http.StripPrefix,但该工具只能在
http.Handlers上使用,而不能在s
http.HandleFunc上使用,因此要使用它,您需要使您适应
HandleFunca
Handler。
这是一个应该执行您想要的工作版本。请注意,wHandler只是从
HttpFunc方法到
Hander接口的适配器:
package mainimport ( "log" "net/http")func serveIDE(w http.ResponseWriter, r *http.Request) { http.FileServer(http.Dir("/home/user/ide")).ServeHTTP(w, r)}func serveConsole(w http.ResponseWriter, r *http.Request) { http.FileServer(http.Dir("/home/user/console")).ServeHTTP(w, r)}type wHandler struct { fn http.HandlerFunc}func (h *wHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { log.Printf("Handle request: %s %s", r.Method, r.RequestURI) defer log.Printf("Done with request: %s %s", r.Method, r.RequestURI) h.fn(w, r)}func main() { http.Handle("/ide", http.StripPrefix("/ide", &wHandler{fn: serveIDE})) http.Handle("/console", http.StripPrefix("/console", &wHandler{fn: serveConsole})) err := http.ListenAndServe(":9090", nil) if err != nil { log.Fatal("ListenAndServe: ", err) }}


