2017-04-25 23 views
0

以下代碼中的任何錯誤?多個目錄服務不能從下面的代碼中運行。當我訪問localhost:9090/ide時,服務器將返回404錯誤。多個Dir服務不起作用

package main 

import (
    "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) 
} 

func main() { 
    http.HandleFunc("/ide", serveIDE)   
    http.HandleFunc("/console", serveConsole) 
    err := http.ListenAndServe(":9090", nil) 
    if err != nil { 
     log.Fatal("ListenAndServe: ", err) 
    } 
} 

當我改變這樣的代碼,

http.HandleFunc("/", serveIDE) 

它將工作如我所料。

回答

3

使用http.FileServer時遇到的問題之一是請求路徑用於構建文件名,所以如果您在除根之外的任何地方提供服務,則需要將路由前綴剝離到該處理程序。

標準庫包括對http.StripPrefix一個有用的工具,但只適用於http.Handler S,不http.HandleFunc S,所以使用它,你需要適應你的HandleFuncHandler

這是一個應該做你想做的工作版本。請注意,wHandler只是從您的HttpFunc方法到Hander接口的適配器:

package main 

import (
     "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) 
     } 
}