我正在探索Go的深度,我一直在尝试编写一个简单的web应用程序来解决所有的问题。我正在尝试提供一个React.js应用程序。
下面是Go服务器的代码。我已经得到了/为index.html服务的默认路径,它运行良好。我很难允许静态文件被送达到那个索引文件中。我允许React完成它自己的客户端路由,尽管我需要静态地服务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)
}
}发布于 2017-05-12 18:01:48
根据大猩猩医学博士,正确的方法是在PathPrefix中注册一个处理程序,如下所示:
router.PathPrefix("/dist/").Handler(http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))如果您在文档中搜索类似于PathPrefix("/static/")的内容,则可以找到一个示例。
这种通配符行为实际上是在默认情况下与net/http中的模式匹配机制一起使用的,因此,如果您没有使用大猩猩,但只使用默认的net/http,则可以执行以下操作:
http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("dist"))))发布于 2017-05-12 17:10:42
文件访问路径可能会出现问题。尝试:
// Strip away "/dist" instead of "/dist/"
router.Handle("/dist/", http.StripPrefix("/dist", http.FileServer(http.Dir("dist"))))https://stackoverflow.com/questions/43943038
复制相似问题