FileServer处理程序与其他一些HTTP处理程序 [英] FileServer handler with some other HTTP handlers
问题描述
我试图在Go中启动一个HTTP服务器,它将使用我自己的处理程序提供自己的数据,但同时我想使用默认的http FileServer来提供文件。
我有问题要使FileServer的处理程序在URL子目录中工作。
此代码不起作用:
p> 包主
导入(
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页未找到
。
但是,如果我将文件服务器的处理程序地址更改为/作品:
/ * ... * /
http.Handle(/,http.FileServer(http .Dir(。)))
但是现在我的文件可以在根目录。
我如何才能使用不同于root的URL来提供文件?
您需要使用 http.StripPrefix
处理程序:
http.Handle(/ files /,http.StripPrefix(/ files /,http.FileServer(http.Dir 。))))
请参阅: http://golang.org/pkg/net/http/#example_FileServer_stripPrefix
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?
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
这篇关于FileServer处理程序与其他一些HTTP处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!