如果URL在Go中没有匹配到任何模式,如何提供文件?

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

How to serve a file if URL doesn't match to any pattern in Go?

问题

我正在使用Angular 2和Go构建一个单页应用程序,并且在Angular中使用路由。如果我在http://example.com/打开网站,Go将为我提供index.html文件,这很好,因为我写了以下代码:

mux.Handle("/", http.FileServer(http.Dir(mysiteRoot)))

现在我在Angular中有一个路由,比如/posts,如果它是一个默认路由(也就是useAsDefaulttrue),或者如果我手动访问http://example.com/posts,我将从Go得到一个404错误,这意味着没有为此路径指定处理程序。

我认为为每个Angular路由在Go中创建一个处理程序不是一个好主意,因为可能有很多路由。所以我的问题是,如果请求的URL与我在ServeMux中设置的任何其他模式都不匹配,我该如何在Go中提供index.html呢?

英文:

I'm building a Single Page Application using Angular 2 and Go, and in Angular I use routing. If I open the site at, say, http://example.com/, Go will serve me my index.html file, which is good because I wrote this:

mux.Handle("/", http.FileServer(http.Dir(mysiteRoot)))

Now I have a route in Angular, let's say, /posts, and If it's a default route (that is, when useAsDefault is true) or if I just manually go to http://example.com/posts, I'll get a 404 error from Go, which means that no handler is specified for this path.

I don't think that creating a handler in Go for every single Angular route is a good idea, because there may be a lot of routes. So my question is, how can I serve index.html in Go if the request URL doesn't match any other pattern that I set in my ServeMux?

答案1

得分: 1

好的,以下是翻译好的内容:

嗯,实际上这很容易。net/http文档提到了这一点:

> 需要注意的是,以斜杠结尾的模式表示一个根子树,模式"/"匹配所有未被其他已注册模式匹配的路径,而不仅仅是Path为"/"的URL。

所以我需要对我的"/"处理程序做一些处理。http.FileServer会在模式字符串指定的目录中查找文件,所以我只需将其替换为以下内容:

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, mysiteRoot + "index.html")
})

然后它就可以正常工作了。

英文:

Well, that was pretty easy actually.
The net/http documentation says this:

> Note that since a pattern ending in a slash names a rooted subtree,
> the pattern "/" matches all paths not matched by other registered
> patterns, not just the URL with Path == "/".

So I needed to do something with my "/" handler. http.FileServer looks for files in a directory that is specified in the pattern string, so I just replaced it with this:

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, mysiteRoot + "index.html")
})

And it works just fine.

答案2

得分: 0

我认为你需要在你的Angular2应用中更改URL提供程序的设置,以使用HashLocationStrategy。使用这个设置,你的路由将采用以下形式:

#/posts

并且不会触发你的Golang应用中的任何路由。

英文:

I think you will need to change the URL provider settings in your angular2 app to use HashLocationStrategy. Using this, your routes will be of the form
>#/posts

and will not trigger any route in your golang app.

huangapple
  • 本文由 发表于 2016年4月10日 02:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/36521237.html
匿名

发表评论

匿名网友

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

确定