【问题标题】:How do I serve CSS and JS in Go如何在 Go 中提供 CSS 和 JS
【发布时间】:2017-09-21 22:02:19
【问题描述】:

我遵循了Go Writing Web Applications 教程,但无论出于何种原因,我都无法让应用程序提供 CSS 和 JS 服务。如果我在没有 Go 服务器的情况下运行我的静态页面,则页面 CSS 可以正常工作。另一方面,当我运行 Go 服务器时,CSS 不起作用。

这是我的 HTML 的样子:

<link rel="stylesheet" href="../assets/css/bootstrap.min.css">
<link rel="stylesheet" href="../assets/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="../assets/css/custom.css">
        

然后在body标签下:

<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>

我的文件树如下所示:

go-affect/
├── data
│   └── …
├── static
│   ├── css
│   │   └── …
│   └── js
│   │   └── …
├── tmpl
│   ├── edit.html
│   ├── index.html
│   └── view.html
└── main.go

如何让我的 Go 应用程序提供我需要的 CSS 和 JavaScript?

编辑:

问题已经解决了,这里是主要工作:

func main() {
    http.HandleFunc("/view/", makeHandler(viewHandler))
    http.HandleFunc("/edit/", makeHandler(editHandler))
    http.HandleFunc("/save/", makeHandler(saveHandler))
    http.HandleFunc("/index/", makeHandler(indexHandler))

    
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

    http.ListenAndServe(":8080", nil)
}

这是我正在使用的处理程序的示例:

func indexHandler(w http.ResponseWriter, r *http.Request, title string) {
    p := &Page{Title: title}
    err := templates.ExecuteTemplate(w, "index.html", p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

【问题讨论】:

标签: go web-applications server


【解决方案1】:
http.Handle("/", http.FileServer(http.Dir("css/")))

将在/ 为您的css 目录提供服务。当然,您可以在您选择的任何路径上提供任何目录。

您可能希望确保静态路径不会妨碍其他路径并使用类似的东西。

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

将您的jscss 都放在项目的static 目录中。这将在domain.com/static/css/filename.cssdomain.com/static/js/filename.js 为他们提供服务

StripPrefix 方法会删除前缀,因此它不会尝试搜索,例如在static/css/filename.cssstatic 目录中,当然,它不会找到。它将在static 目录中查找css/filename.css,这是正确的。

【讨论】:

  • 我应该把那行代码放在哪里?在 main 中包含所有函数处理程序或在我的为索引模板提供服务的函数中,例如
  • 随时。通常在http.ListenAndServe 之前。所以可能在你的主要。
  • 这样做似乎没有奏效。我发布了一些更新的代码
  • 使用我添加到答案中的/static/ 路径,或者为每个css和js做一个,例如http.Handle("/css/", http.FileServer(http.Dir("css/")))http.Handle("/js/", http.FileServer(http.Dir("js/")))
  • 您的代码显示您正在使用http.Dir("/static")。删除/。使用它告诉 Go 在文件系统的根目录中查找目录。否 / 告诉它看起来相对于 go 应用程序。诚然......我的例子有斜线,所以这是我的坏(固定)
【解决方案2】:

我在模板文件的头部添加了一个指向我的 apache 服务器 css 目录的链接。我将任何 go 应用程序使用的模板和数据文件保存在运行 go 应用程序的目录下。在本例中为 cgi-bin。

模板使用我的 apache 服务器 assets/css 目录中的 css :

<link rel="stylesheet" href="/assets/css/main.css" />

go apps run from my cgi-bin dir

sytle sheets are served from my apache assets/css dir

【讨论】:

    猜你喜欢
    • 2021-03-22
    • 2017-08-18
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 2022-12-21
    相关资源
    最近更新 更多