2017-04-25 4 views
0

以下のコードに間違いがありますか?複数のディレクトリサービスが下のコードから機能していません。 localhost:9090/ideにアクセスすると、サーバーは404エラーを返します。私はこのようなコードを変更すると複数のディレクトリサービスが機能していません

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の問題点の1つは、要求パスがファイル名を構築するために使用されるため、ルート以外の場所からアクセスしている場合は、そのハンドラにルートプレフィックスを取り除く必要があることです。

標準ライブラリには、そのhttp.StripPrefixのための有用なツールが含まれていますが、それはだけなので、あなたのHandleFuncHandlerに適応する必要があり、それを使用するために、http.Handler秒、ないhttp.HandleFunc秒で動作します。

ここでは、必要な作業を行うための作業用バージョンがあります。 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) 
     } 
} 
関連する問題