【问题标题】:Golang handle static folderGolang 处理静态文件夹
【发布时间】:2018-08-18 07:39:52
【问题描述】:

我无法获取放置在静态文件夹中的文件。我正在使用 gorilla mux 包。

ma​​in.go 代码:

fs := http.FileServer(http.Dir("static"))
mainRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
http.Handle("/", &mainRouter)

项目结构:

static
templates
--style
--javascript
--...
main.go

当我点击索引页面时:

本地主机:8080/cruise_schedule

我得到了所有样式表和 js 文件,但是当我跳转到另一个页面时:

localhost:8080/cruise_schedule/selected_cruise/e58ed042aad24b9b87fba8917c085534

我收到以下错误:

Refused to apply style from 'http://localhost:8080/cruise_schedule/static/style/style.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

和:

http://localhost:8080/cruise_schedule/static/javascript/resources.js 

我应该怎么做才能正确地提供静态文件?

【问题讨论】:

  • 服务很好(很明显,因为它有效)。问题是您在 HTML 中使用了相对路径,而您应该使用绝对路径(绝对路径以 / 开头)。

标签: go static-files


【解决方案1】:

您的 Go 应用程序没有问题,您生成的 HTML 输出有问题。

您的错误消息表明您的子页面尝试从 http://localhost:8080/cruise_schedule/static/... 加载其 CSS,而实际上 应该http://localhost:8080/static/... 加载。第一个 URL 不会提供静态文件,因为它不在 /static 前缀之下,并且您的应用程序可能会提供其默认的 404 页面(可能是 text/plain 页面)。

为了解决这个问题,我建议您使用绝对路径作为 CSS (<link href="/static/...) 或使用适当的 <base> 标签。

【讨论】:

    猜你喜欢
    • 2018-01-22
    • 2021-07-10
    • 2021-11-01
    • 1970-01-01
    • 2018-07-30
    • 2019-01-09
    • 2021-05-28
    • 1970-01-01
    • 2014-06-06
    相关资源
    最近更新 更多