gpt4 book ai didi

go - 使用 GoLang Web 服务器提供静态内容

转载 作者:IT王子 更新时间:2023-10-29 01:09:05 25 4
gpt4 key购买 nike

我正在探索 Go 的深度,我一直在尝试编写一个简单的 Web 应用程序来解决所有问题。我正在尝试为 React.js 应用程序提供服务。

下面是 Go 服务器的代码。我有 / 服务于 index.html 的默认路由,它工作正常。我正在努力允许将静态文件提供给该索引文件。我允许 React 应用程序执行它自己的客户端路由,尽管我需要静态提供 JavaScript/CSS/媒体文件。

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

网络服务器.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 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"))))

关于go - 使用 GoLang Web 服务器提供静态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43943038/

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