【发布时间】:2017-12-05 15:06:13
【问题描述】:
我在 reactjs 项目中使用 react-router 和 browserHistory 的 pushState。该项目允许用户创建一个创建新路径的注释。为了提供这种类型的网站,我需要为除了静态内容之外的每个路径提供相同的 HTML 文件。所以我的nodejs代码是这样的。
// Serve the static content
app.use('/static/css/', express.static(path.join(__dirname, '../../react-ui/build/static/css')));
app.use('/static/js/', express.static(path.join(__dirname, '../../react-ui/build/static/js')));
app.use('/static/media/', express.static(path.join(__dirname, '../../react-ui/build/static/media')));
app.use('/static/img/', express.static(path.join(__dirname, '../../react-ui/build/static/img')));
app.use('/img/', express.static(path.join(__dirname, '../../react-ui/build/img')));
// Serve the same HTML file to everything else
app.use('*', express.static(path.join(__dirname, '../../react-ui/build')));
我没有看到对 Go FileServer 的任何通配符支持。目前,我使用类似于此的 Go 代码提供所有静态页面。
package main
import (
"net/http"
)
func init(){
fs := http.FileServer(http.Dir("web"))
http.Handle("/", fs)
http.Handle("/static-page-1/", http.StripPrefix("/static-page-1/", fs))
http.Handle("/static-page-2/", http.StripPrefix("/static-page-2/", fs))
http.Handle("/static-page-3/", http.StripPrefix("/static-page-3/", fs))
}
是否可以使用 Go 服务器将内容提供给动态生成的 URL 路径?
如果 Handle 方法支持变量,那么我会这样编写代码
fs := http.FileServer(http.Dir("web"))
http.Handle("/static/", fs)
http.Handle("/{unknownUserPath}", http.StripPrefix("/{unknownUserPath}", fs))
{unknownUserPath} 可以是用户键入的任何不在 /static/ 路径下的路径。
这是 go 项目结构
这是基于@putu 回答的服务器
package main
import (
"net/http"
"strings"
)
func adaptFileServer(fs http.Handler) http.Handler {
fn := func(w http.ResponseWriter, req *http.Request) {
staticIndex := strings.Index(req.URL.Path, "/static/");
imgIndex := strings.Index(req.URL.Path, "/img/");
if staticIndex == -1 && imgIndex == -1 {
fsHandler := http.StripPrefix(req.URL.Path, fs)
fsHandler.ServeHTTP(w, req)
} else {
fs.ServeHTTP(w, req)
}
}
return http.HandlerFunc(fn)
}
func init() {
fs := http.FileServer(http.Dir("web"))
http.Handle("/", adaptFileServer(fs))
}
【问题讨论】:
标签: reactjs google-app-engine go react-router browser-history