gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:04:48 27 4
gpt4 key购买 nike

我正在尝试在 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 提供文件?

最佳答案

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

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

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

关于go - FileServer 处理程序与其他一些 HTTP 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17541333/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com