英文:
Serving static content with GoLang Webserver
问题
我正在探索Go的深度,并且一直在尝试编写一个简单的Web应用程序来理解其中的所有内容。我正在尝试提供一个React.js应用程序。
下面是Go服务器的代码。我已经设置了默认路由/
来提供index.html
,这部分工作正常。我正在努力允许静态文件被提供给该索引文件。我允许React应用程序进行自己的客户端路由,但我需要静态地提供JavaScript/CSS/媒体文件。
例如,我需要能够将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()
// 配置要提供的静态内容。
router.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))
// 路由到客户端应用程序。
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)
}
}
英文:
I'm exploring the depths of Go, and I've been trying to write a simple web application to wrap my head around everything. I'm trying to serve a React.js application.
Below is the code of the Go server. I've got the default route of /
serving the index.html
which is working fine. I'm struggling to allow static files to be served to that index file. I'm allowing the React App to do it's own client side routing, although I need to statically serve the JavaScript / CSS / Media files.
For example, I need to be able to serve the bundle.js
file into the index.html
for the React application to run. Currently, when I route to localhost:8000/dist/
I see the files being listed, but every file/folder that I click from there is throwing a 404 Page Not Found
. Is there something that I'm missing? A push in the right direction would be greatly appreciated.
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)
}
}
答案1
得分: 2
根据gorilla mux文档,正确的方法是使用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"))))
英文:
Per the gorilla mux docs, the proper way to do this would be a handler registered with PathPrefix
, like this:
router.PathPrefix("/dist/").Handler(http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))
An example can be found if you search the docs for something like PathPrefix("/static/")
.
This wildcard behavior actually comes by default with the pattern matching mechanism in net/http, so if you weren't using gorilla, but just the default net/http, you could do the following:
http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))
答案2
得分: 0
可能存在文件访问路径的问题。尝试以下操作:
// 将“/dist”替换为“/dist/”
router.Handle("/dist/", http.StripPrefix("/dist", http.FileServer(http.Dir("dist"))))
英文:
There could be an issue with file access path. Try:
// Strip away "/dist" instead of "/dist/"
router.Handle("/dist/", http.StripPrefix("/dist", http.FileServer(http.Dir("dist"))))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论