微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 在Golang中加载图像和CSS

我在项目根目录的package main中的server.js中设置了一个路由

http.HandleFunc( “/”,route.IndexHandler)

IndexHandler在包路由中实现,如下所示:

func IndexHandler(w http.ResponseWriter,r *http.Request) {
    data:=struct{
        Name string
    }{
        "My name",}
    util.RenderTemplate(w,"index",data)
}

RenderTemplate函数在包util中实现,如下所示:

func RenderTemplate(w http.ResponseWriter,tmpl string,data interface{}) {
    cwd,_ := os.Getwd()
    t,err := template.ParseFiles(filepath.Join(cwd,"./view/" + tmpl + ".html"))
    if err != nil {
        http.Error(w,err.Error(),http.StatusInternalServerError)
        return
    }
    err = t.Execute(w,data)
    if err != nil {
        http.Error(w,http.StatusInternalServerError)
    }
}

项目中的目录结构如下:

/
/public/css
/public/images
/public/js
/route
/view

index.html视图位于文件夹视图中,路由器位于文件夹路径中

在index.html中,我包含以下资源:

< link rel =“stylesheet”type =“text / css”href =“../ public / css / style.css”>

< img src =“../ public / images / img_landing_page_mac.png”>

请求相应路径时,仍会呈现index.html,但不会加载图像和样式表.如何将它们包含在Golang html模板引擎中?

解决方法

您需要明确要求您的服务器提供静态文件.

http.FileServer

在你的情况下注册一个处理程

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Mip是什么意思以及作用有哪些
怎么测试Mip页面运行情况
MIP安装的具体步骤有哪些
HTML添加超链接、锚点的方法及作用详解(附视频)
MIP的规则有哪些
Mip轮播图组件中的重要属性讲解
Mip的内联框架组件是什么
怎么创建初始的MIP配置及模板文件
HTML实现多选框及无法提交多数据的原因分析(附视频)
HTML如何设置复选框、单选框以及默认选项?(图文+视频)