英文:
Golang single page website server
问题
我正在尝试使用Golang和React Router构建一些SPA/SPW,但是我遇到了一个小问题。
React Router似乎基于这样的思想:对于服务器的任何“错误”请求(例如/path/dynamicRessourceHash),都会向用户提供一个.html页面(该HTML页面然后从服务器导入.js),然后React Router会分析路径并提供应用程序所需的信息,以便在后台进行fetch请求并将资源提供给用户。
那么,使用标准库"net/http"配置这样的服务器的标准方法是什么?即,在预配置的端点上正常提供资源,但将所有其他端点视为一个(或少数几个)路由的通配符?
举个例子(因为今天我似乎不擅长用文字表达)。假设用户发出以下请求:
/route1/whatever/someotherstuff?...等等,第二个“/”后面的内容是什么,我希望用户由/route1/的处理函数提供服务(注意,我不希望用户被重定向,因为那会破坏URL,从而破坏客户端路由)。
英文:
I'm trying to build some spa/spw with golang and react-router as the back-end, but I've encountered a little problem.
React-router seems to base itself around the idea that any "bad" request to the server (e.g. /path/dynamicRessourceHash ) delivers an .html page the user (said html page then imports the .js from the server) and react-router then kicks in, analyzes the path and gives the application the information needed to make fetch requests in the background and deliver the resources to the user.
So what would be the standard way to configure a server like this using "net/http" from std , that is, to server resources normally on pre-configured endpoints but treat all other endpoints as wildcards for one (or few) routes ?
Just to give an example (since today I seem to be bad with words). Say the user makes a request at:
/route1/whatever/someotherstuff?... etc whatever the things after the second "/" are I want the user to be served by the handler function for /route1/ (Note, i don't want the user to be redirected, since that fucks up the URL and consequently the client-side routing).
答案1
得分: 2
在net/http
中,你可以使用处理程序来为/
路由返回一个404页面,因为所有未知/未注册的路由都匹配/
。
http.HandleFunc("/", handler)
...
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
// 将自定义的404页面写入w.Write()
return
}
// 处理路由为/的情况
}
你还可以使用支持Not Found Handlers
的不同的HTTP多路复用器。
例如:
在httprouter
中,你可以设置httprouter.Router.NotFound
或者
在gorilla/mux
中,你可以设置mix.Router.NotFoundHandler
英文:
In net/http
you can use the handler than serves the /
route to return a 404 page since all unknown / unregistered routes match /
.
http.HandleFunc("/", handler)
...
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
// Write custom 404 Page to w.Write()
return
}
// Handling for route /
}
You could also use a different http multiplexer that supports Not Found Handlers
.
Eg.
In httprouter
you set httprouter.Router.NotFound
OR
In gorilla/mux
you set mix.Router.NotFoundHandler
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论