gpt4 book ai didi

go - 当请求到达根目录时,从另一个目录提供文件

转载 作者:行者123 更新时间:2023-12-01 22:17:06 25 4
gpt4 key购买 nike

当客户端请求进入根目录时,从子目录提供某些文件时遇到麻烦。

我正在使用gorilla/mux提供文件。这是我的代码如下:

package main

import (
"log"
"net/http"
"time"

"github.com/gorilla/mux"
"github.com/zhughes3/zacharyhughes.com/configparser"
)

var config configparser.Configuration

func main() {
config := configparser.GetConfiguration()
r := mux.NewRouter()
initFileServer(r)

server := &http.Server{
Handler: r,
Addr: ":" + config.Server.Port,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}

log.Fatal(server.ListenAndServe())
}

func initFileServer(r *mux.Router) {
fs := http.FileServer(http.Dir("public/"))
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", fs))
}

创建文件系统的代码在上面的 initFileServer函数中。

当前,当用户转到 localhost:3000/public/时,它将按预期提供静态文件。但是,我希望在用户转到 localhost:3000/时提供文件。

我尝试将ParsePrefix函数调用更改为 r.PathPrefix("/").Handler(http.StripPrefix("/public/", fs)),但没有用。任何建议将不胜感激...我对Go很陌生。

最佳答案

您的文件服务器已经在/public下提供文件,因此您无需从http路径中删除前缀。这应该工作:

    r.PathPrefix("/").Handler(http.StripPrefix("/",fs))

关于go - 当请求到达根目录时,从另一个目录提供文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58887311/

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