go web template css js 靜態資源引用
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
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
如果css js 始終載入無效,運行當前頁面, 打開瀏覽器如下位置
把滑鼠放在文件上方 會顯示文件的路徑 或者右擊 選擇 Open in new tab , 看是否可以打開, 如果不可以 那就證明是路徑的問題 你需要根據你的目錄層級關係定義路由到具體文件的前一個文件夾
※Linux系統狀態查看命令
※確保Docker安全的10款頂尖開源工具
TAG:程序員小新人學習 |