使用GoLang Web服务器提供静态内容
我正在探索Go的深度,我一直在尝试编写一个简单的web应用程序,让我对所有事情都了如指掌。我正在尝试为React.js应用程序提供服务 下面是Go服务器的代码。我已经有了默认的使用GoLang Web服务器提供静态内容,go,Go,我正在探索Go的深度,我一直在尝试编写一个简单的web应用程序,让我对所有事情都了如指掌。我正在尝试为React.js应用程序提供服务 下面是Go服务器的代码。我已经有了默认的/路由,为index.html服务,它工作得很好。我正在努力允许静态文件被提供给那个索引文件。我允许React应用程序执行自己的客户端路由,尽管我需要静态地提供JavaScript/CSS/媒体文件 例如,我需要能够将bundle.js文件提供到index.html中,以便React应用程序运行。目前,当我路由到local
/
路由,为index.html
服务,它工作得很好。我正在努力允许静态文件被提供给那个索引文件。我允许React应用程序执行自己的客户端路由,尽管我需要静态地提供JavaScript/CSS/媒体文件
例如,我需要能够将bundle.js
文件提供到index.html
中,以便React应用程序运行。目前,当我路由到localhost:8000/dist/
时,我看到列出的文件,但我从那里单击的每个文件/文件夹都会抛出一个404页面,找不到。有什么我遗漏的吗?如果能朝着正确的方向努力,我们将不胜感激
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)
}
}
文件访问路径可能存在问题。尝试:
// Strip away "/dist" instead of "/dist/"
router.Handle("/dist/", http.StripPrefix("/dist", http.FileServer(http.Dir("dist"))))
根据,正确的方法是使用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"))))
希望对大猩猩更精通的人能回答你的问题。你使用gorilla mux做这个有什么原因吗?看来stdlibmux可以很好地处理这个问题。我不认为是库造成了问题。我尝试过移除大猩猩,我也遇到了同样的问题。Gorilla的理由是在以后看看API和身份验证服务的全部内容,但仍然不起作用。浏览器或cURL中的URL为http://localhost:8000/dist/filename.js
。我将进行一些日志记录,以确保请求与文件名之间可能存在差异。如果句柄URL与StripPrefix相同,那么一旦您尝试访问该文件,它就会从URL中删除/dist/
。