doucan8521 2016-04-09 18:53
浏览 40
已采纳

如果URL与Go中的任何模式都不匹配,如何提供文件?

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?

  • 写回答

2条回答 默认 最新

  • douche3244 2016-04-09 20:24
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行