http handler 绑定相同地址,求助

2017-10-26 09:52:22 +08:00
 zgoing
希望在"/"下注册 FileServer,同时也想在浏览器访问 /时发送 index.html 文件,请问有什么办法可以实现呢。google 一下只能找到 15 年 github 上的一个 issue,最后也还是没有解决
1103 次点击
所在节点    Go 编程语言
5 条回复
boboliu
2017-10-26 09:57:33 +08:00
可以写个 handler,当 URL 为 /时返回 index,别的返回 FileServe

其实最简单的还是把 index 放在目标目录吧(手动滑稽
zgoing
2017-10-26 10:04:43 +08:00
@boboliu @boboliu 非常感谢
freestyle
2017-10-29 23:47:19 +08:00
@zgoing
@boboliu
http.FileServer 会自动处理 index.html 的, 你看代码 https://github.com/golang/go/blob/master/src/net/http/fs.go#L592-L605

比如 http.Handle("/", http.FileServer( http.Dir("assets"))), 在 assets 文件夹下如果有 index.html, 就会显示出来


package main

import (
"net/http"
"log"
)

func main() {
http.Handle("/", http.FileServer( http.Dir("assets")))
log.Print("http file server start at :8000")
log.Fatal( http.ListenAndServe(":8000", nil))
}
zgoing
2017-10-30 06:24:40 +08:00
@freestyle #3 谢谢说明,学习了
boboliu
2017-10-30 06:42:12 +08:00
@freestyle 感谢说明,在下还是不熟练啊_(:з」∠)_

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/400828

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX