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

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

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)
}

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:

确定