登录
首页 >  Golang >  Go问答

嵌入式文件系统如何正确提供使用 html/template 生成的内容

来源:stackoverflow

时间:2024-02-10 14:45:23 105浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《嵌入式文件系统如何正确提供使用 html/template 生成的内容》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

当我在浏览器上访问 localhost:8080 时,我得到一个显示模板中正确字段值的页面,但是,css 无法正确加载。当我访问浏览器上的 web 开发人员工具面板时,我注意到 .js.css 文件有两个相同的错误,即

the resource from “http://localhost:8080/static/style.css” was blocked due to mime type (“text/plain”) mismatch (x-content-type-options: nosniff).

(我只显示与 .css 文件相关的错误,其他相同)

我真的不知道还能做什么,因为我已经尝试了所有简单的解决方案,例如修改相对路径或在与 main.go 相同的级别构建二进制文件并从那里运行服务器。 p>

据我所知,嵌入对 templates 文件夹有效,但似乎对 static 文件夹的内容不起作用。我认为我没有错说,虽然服务器成功加载模板,但在解析 dom 时无法找到 /static/styles.css (对于 .js 文件也是如此)(它找不到/静态/文件夹)。

在这一点上,任何人的猜测都和我的一样好。

我做错了什么?为什么服务器无法成功路由 \static\ 文件夹?我的代码还有其他问题吗?

老实说,我现在看到的是胡言乱语。欢迎任何帮助。谢谢

我的代码

我的文件夹结构如下

static
    |
    script.js
    styles.css
templates
    |
    template.html
handler.go
main.go

这是我的 main.go

package main

import (
    "embed"
    "fmt"
    "net/http"
)

//go:embed static templates
var content embed.fs

func main() {
    // define the handler function for the page to display
    http.handlefunc("/", handler)

    // serve the static files (css, js, images) from the "static" directory
    http.handle("/static/", http.stripprefix("/static/", http.fileserver(http.fs(content))))

    // start the server on port 8080
    http.listenandserve(":8080", nil)
}

这是我的 handler.go 文件:

package main

import (
    "html/template"
    "net/http"
    "time"

    /* other imports */
)

func handler(w http.responsewriter, r *http.request) {
    // define the template data
    data, err := /* code that returns data for the template */
    if err != nil {
        panic(err) // i wasn't sure how to handle this
    }

    // parse the template file
    tmpl, err := template.parsefs(content, "templates/template.html")
    if err != nil {
        http.error(w, err.error(), http.statusinternalservererror)
        return
    }

    // execute the template with the data
    err = tmpl.execute(w, data)
    if err != nil {
        http.error(w, err.error(), http.statusinternalservererror)
        return
    }
}

这是我的 template.html 文件:




    Countdown
    


    

Title

/* here is code accessing the fields of the data passed to the template */

我不提供 script.js 文件,因为它暂时是空的,而且它引起的问题与 style.css 的问题相同。


正确答案


static 不是文件系统的根目录,因此 http.stripprefix 不是必需的。

使用它,对 /static/some-file.js 的请求会在文件系统中查找 /some-file.js 。如果没有它,/static/ 会被保留,这就是文件系统的实际布局方式。

所以,你想要:

// Serve the static files (CSS, JS, images) from the "static" directory
http.Handle("/static/", http.FileServer(http.FS(content)))

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>