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

时间:2013-07-09 06:23:04

标签: go

我正在尝试使用自己的处理程序在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提供文件?

1 个答案:

答案 0 :(得分:19)

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

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

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

相关问题