文件服务器处理程序与其他一些HTTP处理程序

huangapple go评论88阅读模式
英文:

FileServer handler with some other HTTP handlers

问题

我正在尝试在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页面未找到”。

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

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

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

如何使其从不同的URL而不是根目录提供文件?

英文:

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

得分: 22

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

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

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

英文:

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

huangapple
  • 本文由 发表于 2013年7月9日 14:23:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/17541333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定