我在reactjs項目中使用react-router和browserHistory的pushState。該項目讓用戶創建一個創建新路徑的註釋。爲了提供這種類型的網站,我需要爲靜態內容以外的每個路徑提供相同的HTML文件。所以我的nodejs代碼看起來像這樣。如何使用Go來動態創建URL路徑?
// 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))
}
是否有可能成爲內容動態生成與進入服務器的URL路徑?
如果處理方法支持的變量,那麼我寫這樣
fs := http.FileServer(http.Dir("web"))
http.Handle("/static/", fs)
http.Handle("/{unknownUserPath}", http.StripPrefix("/{unknownUserPath}", fs))
{} unknownUserPath的代碼將任意路徑,在用戶鍵入沒有受到/靜態/路徑。
這裏的圍棋項目結構
下面是基於@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))
}
謝謝!我能夠讓文件服務器在沒有多路複用服務器對象的情況下工作,但如果我想添加任何服務,那麼我需要使用它。我將我用的代碼添加到了我的問題中 – sissonb