多个目录服务不起作用

Any mistakes in below code? Multiple directory serving is not working from the below code. When I access the localhost:9090/ide, the server will return 404 error.

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)
    }
}

When I change the code like this,

http.HandleFunc("/", serveIDE)

It will work as I expected.

One of the issues with using http.FileServer is that the request path is used to build the file name, so if you're serving from anywhere but the root you need to strip the route prefix to that handler.

The standard library includes a helpful tool for that http.StripPrefix, but that only works on http.Handlers, not http.HandleFuncs, so to use it you need to adapt your HandleFunc to a Handler.

Here is a working version that should do what you want. Note that wHandler is just an adapter from your HttpFunc methods to Hander interface:

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)
        }
}