如何设置Go服务器以与AngularJS的html5mode兼容?

huangapple go评论109阅读模式
英文:

How do you set up the go server to be compatible with AngularJS html5mode?

问题

我正在使用julienschmidt/httprouter和http.FileServer。

类似这样:

  1. func main() {
  2. router := httprouter.New()
  3. router.NotFound = http.FileServer(http.Dir("/srv/www/public_html"))
  4. router.GET("/api/user/:id", getUserbyId)
  5. log.Fatal(http.ListenAndServe(":80", router))
  6. }

所以如果找不到路由,就从根目录"/"中提供文件。

但是这并没有按预期工作。在nginx中,我是这样做的:

  1. location / {
  2. autoindex on;
  3. try_files $uri $uri/ /index.html =404;
  4. }

检查给定URL中是否有任何文件,如果没有,则提供/index.html给他们。

如何使服务器与AngularJS的html5mode兼容?

英文:

I am using the julienschmidt/httprouter alongside with http.FileServer.

Something like this:

  1. func main() {
  2. router := httprouter.New()
  3. router.NotFound = http.FileServer(http.Dir("/srv/www/public_html"))
  4. router.GET("/api/user/:id", getUserbyId)
  5. log.Fatal(http.ListenAndServe(":80", router))
  6. }

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

  1. location / {
  2. autoindex on;
  3. try_files $uri $uri/ /index.html =404;
  4. }

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

如果找不到路由,请添加以下代码:

  1. router.GET("/", Yourfunction)

并将您的函数定义如下:

  1. func Yourfunction(res http.ResponseWriter, req *http.Request) {
  2. file, _ := ioutil.ReadFile("/srv/www/public_html")
  3. t := template.New("")
  4. t, _ = t.Parse(string(file))
  5. t.Execute(res, nil)
  6. }
英文:

If route is not found, add

  1. router.GET("/", Yourfunction)

and your function as,

  1. func Yourfunction(res http.ResponseWriter, req *http.Request) {
  2. file, _ := ioutil.ReadFile("/srv/www/public_html")
  3. t := template.New("")
  4. t, _ = t.Parse(string(file))
  5. t.Execute(res, nil)
  6. }

huangapple
  • 本文由 发表于 2015年7月7日 16:40:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/31263727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定