小编典典

多个目录服务不起作用

go

下面的代码有任何错误吗?以下代码无法提供多个目录服务。当我访问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)

它会按我预期的那样工作。


阅读 232

收藏
2020-07-02

共1个答案

小编典典

使用中的问题之一http.FileServer是请求路径用于构建文件名,因此,如果要从根目录以外的任何地方提供服务,则需要剥离到该处理程序的路由前缀。

标准库为此提供了一个有用的工具http.StripPrefix,但该工具只能在http.Handlers上使用,而不能在s
http.HandleFunc上使用,因此要使用它,您需要使您适应HandleFunca Handler

这是一个应该执行您想要的工作版本。请注意,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)
        }
}
2020-07-02