【问题标题】:Serving static content with GoLang Webserver使用 GoLang Webserver 提供静态内容
【发布时间】:2017-05-12 17:04:07
【问题描述】:

我正在探索 Go 的深度,并且一直在尝试编写一个简单的 Web 应用程序来涵盖所有内容。我正在尝试为 React.js 应用程序提供服务。

下面是 Go 服务器的代码。我有/ 的默认路由为index.html 服务,它工作正常。我正在努力允许将静态文件提供给该索引文件。我允许 React App 做它自己的客户端路由,虽然我需要静态地提供 JavaScript / CSS / Media 文件。

例如,我需要能够将 bundle.js 文件提供到 index.html 中,以便 React 应用程序运行。目前,当我路由到localhost:8000/dist/ 时,我看到列出的文件,但是我从那里单击的每个文件/文件夹都会抛出404 Page Not Found。有什么我想念的吗?非常感谢您朝着正确的方向前进。

Webserver.go

package main

import (
    "net/http"
    "log"
    "fmt"
    "os"

    "github.com/BurntSushi/toml"
    "github.com/gorilla/mux"
)

type ServerConfig struct {
    Environment string
    Host string
    HttpPort int
    HttpsPort int
    ServerRoot string
    StaticDirectories []string
}

func ConfigureServer () ServerConfig {
    _, err := os.Stat("env.toml")
    if err != nil {
        log.Fatal("Config file is missing: env.toml")
    }

    var config ServerConfig
    if _, err := toml.DecodeFile("env.toml", &config); err != nil {
        log.Fatal(err)
    }

    return config
}

func IndexHandler (w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "./src/index.html")
}

func main () {
    Config := ConfigureServer()
    router := mux.NewRouter()

    // Configuring static content to be served.
    router.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))

    // Routing to the Client-Side Application.
    router.HandleFunc("/", IndexHandler).Methods("GET")

    log.Printf(fmt.Sprintf("Starting HTTP Server on Host %s:%d.", Config.Host, Config.HttpPort))

    if err := http.ListenAndServe(fmt.Sprintf("%s:%d", Config.Host, Config.HttpPort), router); err != nil {
        log.Fatal(err)
    }
}

【问题讨论】:

  • 希望更精通大猩猩的人可以回答您的问题。您为此使用 gorilla mux 有什么原因吗?似乎 stdlib 多路复用器可以很好地处理这个问题。
  • 我不认为是库引起了问题。我已经尝试过移除大猩猩,但我遇到了同样的问题。 Gorilla 的理由是稍后再看看 API 和 Auth 服务的全部内容。

标签: go


【解决方案1】:

根据gorilla mux docs,正确的做法是使用PathPrefix 注册处理程序,如下所示:

router.PathPrefix("/dist/").Handler(http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))

如果您在文档中搜索 PathPrefix("/static/") 之类的内容,可以找到一个示例。


这种通配符行为实际上是在 net/http 中的模式匹配机制中默认出现的,所以如果您没有使用 gorilla,而只是使用默认的 net/http,您可以执行以下操作:

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

【讨论】:

    【解决方案2】:

    文件访问路径可能存在问题。试试:

    // Strip away "/dist" instead of "/dist/"
    router.Handle("/dist/", http.StripPrefix("/dist", http.FileServer(http.Dir("dist"))))
    

    【讨论】:

    • 还是不行。浏览器或 cURL 中的 URL 是http://localhost:8000/dist/filename.js。我会做一些记录以确保请求与文件名可能。
    • 如果句柄 URL 与 StripPrefix 相同,那么一旦您尝试访问文件,它就会从 URL 中删除 /dist/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2014-12-06
    • 2011-10-14
    • 2014-07-30
    • 1970-01-01
    相关资源
    最近更新 更多