GO:提供静态页面

时间:2014-07-27 12:25:02

标签: go

我试图用GO显示静态页面。

GO:

package main

import "net/http"

func main() {
    fs := http.FileServer(http.Dir("static/home"))
    http.Handle("/", fs)
    http.ListenAndServe(":4747", nil) 
}

目录:

Project
    /static
        home.html
        edit.html
    project.go

当我运行它时,网页会显示指向edit.html和home.html的链接,而不是显示home.html中的静态页面。我究竟做错了什么。这是提供文件的最佳方式吗?我知道还有其他方法,例如。来自html / templates包,但我不确定区别是什么以及何时使用这些方法。谢谢!

2 个答案:

答案 0 :(得分:2)

func main() {
    http.Handle("/", http.FileServer(http.Dir("static")))
    http.ListenAndServe(":4747", nil)
}

您不需要static/home,只需static

FileServer正在使用directory listing,因为index.html中没有/static,所以会显示目录内容。

快速解决方法是将home.html重命名为index.html。这样,您就可以通过index.html访问http://localhost:4747/edit.html访问http://localhost:4747/edit.html

如果您只需要提供静态文件,则无需使用html/template

但一个干净的解决方案取决于你实际上要做的事情。

答案 1 :(得分:1)

如果您只对编写一个提供静态内容的简单服务器感兴趣,而不仅仅是作为一种学习体验,我会看一下Martini(http://martini.codegangsta.io/)。

典型的Martini应用程序,用于提供名为' public'的文件夹中的静态文件。将是:

package main

import (
    "github.com/go-martini/martini"
)

func main() {
    m := martini.Classic()
    m.Run()
}

添加名为' static'的新静态文件夹搜索内容的静态文件夹列表也很简单:

package main

import (
    "github.com/go-martini/martini"
)

func main() {
    m := martini.Classic()
    m.Use(martini.Static("static")) // serve from the "static" directory as well
    m.Run()
}

Martini还提供了更多功能,例如会话,模板渲染,路线处理程序等......

我们在这里使用Martini进行生产,对它及其周围的基础设施非常满意。

相关问题