drcb19700 2017-04-25 02:51
浏览 4
已采纳

多个目录服务不起作用

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.

  • 写回答

1条回答 默认 最新

  • douxianliu6756 2017-04-25 03:11
    关注

    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)
            }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器