我正在尝试在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!")
}
Run Code Online (Sandbox Code Playgroud)
我期待在localhost:1234/files /中找到本地目录,但它返回一个404 page not found
.
但是,如果我将文件服务器的处理程序地址更改为/,它可以工作:
/* ... */
http.Handle("/", http.FileServer(http.Dir(".")))
Run Code Online (Sandbox Code Playgroud)
但现在我的文件可以在根目录下访问和查看.
如何使其从不同于root的URL提供文件?
aki*_*ira 21
您需要使用http.StripPrefix
处理程序:
http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir("."))))
Run Code Online (Sandbox Code Playgroud)
请参见此处:http://golang.org/pkg/net/http/#example_FileServer_stripPrefix
归档时间: |
|
查看次数: |
7974 次 |
最近记录: |