【问题标题】:GO: Serve static pagesGO:提供静态页面
【发布时间】:2023-03-13 12:44:01
【问题描述】:

我正在尝试使用 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 包,但我不确定有什么区别以及何时使用这些方法。谢谢!

【问题讨论】:

标签: go


【解决方案1】:
func main() {
    http.Handle("/", http.FileServer(http.Dir("static")))
    http.ListenAndServe(":4747", nil)
}

您不需要static/home,只需static

FileServer 使用的是directory listing,由于您在/static 中没有index.html,因此会显示目录内容。

快速解决方法是将home.html 重命名为index.html。这将允许您通过http://localhost:4747/edit.htmlhttp://localhost:4747/edit.html 访问index.html

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

但干净的解决方案取决于您实际尝试做的事情。

【讨论】:

    【解决方案2】:

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

    从名为“public”的文件夹中提供静态文件的典型 Martini 应用是:

    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,并且对它及其周围的基础设施非常满意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2014-08-22
      • 2019-11-14
      • 2014-11-12
      • 1970-01-01
      • 2013-02-20
      • 2016-09-14
      相关资源
      最近更新 更多