【问题标题】:Serve files from a different directory when request comes to root directory当请求到达根目录时,从不同的目录提供文件
【发布时间】:2019-11-16 03:34:58
【问题描述】:

当客户端请求进入根目录时,我无法从子目录中提供一些文件。

我正在使用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 很陌生。

【问题讨论】:

    标签: go mux go-http


    【解决方案1】:

    您的文件服务器已经在 /public 下提供文件,因此您不需要从 http 路径中去除前缀​​。这应该有效:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      相关资源
      最近更新 更多