为了账号安全,请及时绑定邮箱和手机立即绑定

在 Golang 中加载图像和 css

在 Golang 中加载图像和 css

Go
拉莫斯之舞 2021-12-20 15:57:22
我在项目的根目录server.js中的包main中设置了一个路由http.HandleFunc("/",route.IndexHandler)将IndexHandler在封装中实现route这样的: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, err.Error(), http.StatusInternalServerError)    }}项目中的目录结构如下://public/css/public/images/public/js/route/viewindex.html视图位于文件夹中view,路由器位于文件夹中route在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 模板引擎中?
查看完整描述

2 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

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

http.FileServer

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

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


查看完整回答
反对 回复 2021-12-20
?
交互式爱情

TA贡献1712条经验 获得超3个赞

就像Aruna说的,注册一个静态文件服务器句柄

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

要使用 HTML 中的文件,只需

<img src="/public/images/img_landing_page_mac.png">


查看完整回答
反对 回复 2021-12-20
  • 2 回答
  • 0 关注
  • 214 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号