dongzaobei0942 2013-07-09 06:23
浏览 38
已采纳

FileServer处理程序和其他一些HTTP处理程序

I'm trying to start a HTTP server in Go that will serve my own data using my own handlers, but at the same time I would like to use the default http FileServer to serve files.

I'm having problems to make the handler of the FileServer to work in a URL subdirectory.

This code is not working:

package main

import (
        "fmt"
        "log"
        "net/http"
)

func main() {
        http.Handle("/files/", http.FileServer(http.Dir(".")))
        http.HandleFunc("/hello", myhandler)

        err := http.ListenAndServe(":1234", nil)
        if err != nil {
                log.Fatal("Error listening: ", err)
        }
}

func myhandler(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintln(w, "Hello!")
}

I was expecting to find the local directory in localhost:1234/files/ but it returns a 404 page not found.

However, if I change the handler address of the fileserver to /, it works:

        /* ... */
        http.Handle("/", http.FileServer(http.Dir(".")))

But now my files are accessible and visible at the root directory.

How can I make it to serve files from a different URL than root?

  • 写回答

1条回答 默认 最新

  • dongxin2734 2013-07-09 06:31
    关注

    You need to use the http.StripPrefix handler:

    http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("."))))
    

    See here: http://golang.org/pkg/net/http/#example_FileServer_stripPrefix

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信
  • ¥30 Python调用dll文件输出Nan重置dll状态
  • ¥15 浮动div的高度控制问题。
  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论