go web template css js 静态资源引用

本文介绍了在Go Web应用中引用CSS和JS等静态资源的方法。通过项目结构的展示和`web.go`及`web.gtpl`的代码示例,讲解了如何正确设置和访问静态文件。当遇到资源加载无效时,可以通过检查浏览器开发者工具中的文件路径来定位问题,确保静态资源的路径正确无误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、项目结构
我项目的目录结构
2、web.go (go 后端代码)

package main

import (
	"net/http"
    // "fmt"
    "html/template"
)

//网站首页
func index(w http.ResponseWriter ,r *http.Request){
    t,_ := template.ParseFiles("view/web.gtpl")  //加载模板文件
    t.Execute(w,nil)    //模板文件显示在页面上
    // fmt.Fprintf(w,"<h1>go web</h1>")  //直接显示在页面上
}

func main(){

    //静态资源的引用  我之前是用的 /static/ 然后模板中写的是 /static/css/然后访问不到css  
    //所以路由应该需要指到具体文件的当前文件夹名   eg: /static/css/1.css  如果渲染1.css 需注册路由/static/css/
    http.Handle("/static/css/", http.StripPrefix("/static/css/", http.FileServer(http.Dir("static/css/")))) 
    http.Handle("/static/js/", http.StripPrefix("/static/js/", http.FileServer(http.Dir("static/js/"))))
    http.Handle("/static/images/", http.StripPrefix("/static/images/", http.FileServer(http.Dir("static/images/"))))
    http.Handle("/static/fonts/", http.StripPrefix("/static/fonts/", http.FileServer(http.Dir("static/fonts/"))))

    http.HandleFunc("/",index)   //路由 网站是当前这种路径时调用index  (类似nginx的rewrite 根据不同的路径调用不同的方法 )
    http.ListenAndServe(":9090",nil)  //http的localhost运行时的端口 eg:http://localhost:9090
}

3、web.gtpl (前台代码)

<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<link href="/static/css/bootstrap.css" rel="stylesheet" type="text/css" media="all" />
<link rel="stylesheet" href="/static/css/swipebox.css">
<script src="/static/js/jquery-1.11.1.min.js"></script>
<body>
	<div class="top-header-agile">
		<div class="container">
			<div class="col-md-6 top-header-agile-left">
				<ul>
					<li><i class="fa fa-phone" aria-hidden="true"></i></li>
					<li>+18084563326</li>
					<li><i class="fa fa-envelope" aria-hidden="true"></i></li>
					<li><a href="mailto:info@example.com">info@example.com</a></li>
				</ul>
			</div>
			<div class="col-md-6 top-header-agile-right">
				<ul>
					<li><a href="#"><i class="fa fa-twitter" aria-hidden="true"></i></a></li>
					<li><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li>
					<li><a href="#"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li>
					<li><a href="#"><i class="fa fa-dribbble" aria-hidden="true"></i></a></li>
				</ul>
			</div>
			<div class="clearfix"></div>
		</div>
	</div>
</div>

在运行项目之前你需要go run web.go (就是你的那个入口文件) 或者 go build web.go 生成一个.exe的文件 然后运行.exe 的文件 再访问localhost:9090

如果css js 始终加载无效,运行当前页面, 打开浏览器如下位置
找到不能显示的js css
把鼠标放在文件上方 会显示文件的路径 或者右击 选择 Open in new tab , 看是否可以打开, 如果不可以 那就证明是路径的问题 你需要根据你的目录层级关系定义路由到具体文件的前一个文件夹

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值