【问题标题】:FileServer handler with some other HTTP handlersFileServer 处理程序与其他一些 HTTP 处理程序
【发布时间】:2013-07-09 14:31:52
【问题描述】:

我正在尝试在 Go 中启动一个 HTTP 服务器,它将使用我自己的处理程序来提供我自己的数据,但同时我想使用默认的 http FileServer 来提供文件。

我在使 FileServer 的处理程序在 URL 子目录中工作时遇到问题。

此代码不起作用:

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

我希望在 localhost:1234/files/ 中找到本地目录,但它返回 404 page not found

但是,如果我将文件服务器的处理程序地址更改为 /,它可以工作:

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

但现在我的文件可以在根目录中访问和查看。

我怎样才能让它从不同于 root 的 URL 提供文件?

【问题讨论】:

    标签: go


    【解决方案1】:

    您需要使用http.StripPrefix 处理程序:

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

    请看这里:http://golang.org/pkg/net/http/#example_FileServer_stripPrefix

    【讨论】:

    • 哦,它就在文件服务器示例的下方,我觉得很愚蠢......谢谢!
    猜你喜欢
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多