英文:
How do you set up the go server to be compatible with AngularJS html5mode?
问题
我正在使用julienschmidt/httprouter和http.FileServer。
类似这样:
func main() {
router := httprouter.New()
router.NotFound = http.FileServer(http.Dir("/srv/www/public_html"))
router.GET("/api/user/:id", getUserbyId)
log.Fatal(http.ListenAndServe(":80", router))
}
所以如果找不到路由,就从根目录"/"中提供文件。
但是这并没有按预期工作。在nginx中,我是这样做的:
location / {
autoindex on;
try_files $uri $uri/ /index.html =404;
}
检查给定URL中是否有任何文件,如果没有,则提供/index.html给他们。
如何使服务器与AngularJS的html5mode兼容?
英文:
I am using the julienschmidt/httprouter alongside with http.FileServer.
Something like this:
func main() {
router := httprouter.New()
router.NotFound = http.FileServer(http.Dir("/srv/www/public_html"))
router.GET("/api/user/:id", getUserbyId)
log.Fatal(http.ListenAndServe(":80", router))
}
So if a route is not found just serve them from root dir "/"
But this does not work as intended. In nginx I do it like this
location / {
autoindex on;
try_files $uri $uri/ /index.html =404;
}
Check if there are any files in the given url, if not then give them /index.html
How can I make the server compatible with AngularJS html5mode?
答案1
得分: 1
如果找不到路由,请添加以下代码:
router.GET("/", Yourfunction)
并将您的函数定义如下:
func Yourfunction(res http.ResponseWriter, req *http.Request) {
file, _ := ioutil.ReadFile("/srv/www/public_html")
t := template.New("")
t, _ = t.Parse(string(file))
t.Execute(res, nil)
}
英文:
If route is not found, add
router.GET("/", Yourfunction)
and your function as,
func Yourfunction(res http.ResponseWriter, req *http.Request) {
file, _ := ioutil.ReadFile("/srv/www/public_html")
t := template.New("")
t, _ = t.Parse(string(file))
t.Execute(res, nil)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论