V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
zgoing
V2EX  ›  Go 编程语言

http handler 绑定相同地址,求助

  •  
  •   zgoing · 2017-10-26 09:52:22 +08:00 via iPhone · 1088 次点击
    这是一个创建于 2345 天前的主题,其中的信息可能已经有所发展或是发生改变。
    希望在"/"下注册 FileServer,同时也想在浏览器访问 /时发送 index.html 文件,请问有什么办法可以实现呢。google 一下只能找到 15 年 github 上的一个 issue,最后也还是没有解决
    5 条回复    2017-10-30 06:42:12 +08:00
    boboliu
        1
    boboliu  
       2017-10-26 09:57:33 +08:00 via Android   ❤️ 1
    可以写个 handler,当 URL 为 /时返回 index,别的返回 FileServe

    其实最简单的还是把 index 放在目标目录吧(手动滑稽
    zgoing
        2
    zgoing  
    OP
       2017-10-26 10:04:43 +08:00 via iPhone
    @boboliu @boboliu 非常感谢
    freestyle
        3
    freestyle  
       2017-10-29 23:47:19 +08:00   ❤️ 1
    @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
        4
    zgoing  
    OP
       2017-10-30 06:24:40 +08:00
    @freestyle #3 谢谢说明,学习了
    boboliu
        5
    boboliu  
       2017-10-30 06:42:12 +08:00 via Android
    @freestyle 感谢说明,在下还是不熟练啊_(:з」∠)_
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5332 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 09:15 · PVG 17:15 · LAX 02:15 · JFK 05:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.