[實作] 從零開始用 Golang 寫網頁 : 04 靜態網頁的處理方式
當網頁需要用到 js、css、圖片等時,並不需要透過 HandleFunc 來匹配並透過相對應函式輸出,可以直接使用 Handle 來匹配,不必再透過函式輸出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | func main() { 	http.HandleFunc("/", myWeb)
  	staticHandle := http.FileServer(http.Dir("./static"))
  	http.Handle("/js/", staticHandle)
  	fmt.Println("服務器即將開啟, 訪問地址 http://localhost:8080")
  	err := http.ListenAndServe(":8080", nil)
  	if err != nil { 		fmt.Println("服務器開啟錯誤 : ", err) 	} }
  | 
 
main
1
   | http.Handle("/js/", http.FileServer(http.Dir("./static")))
  | 
 
1
   | alert("Javascript running...");
  | 
 
- 最後在上一篇的 HTML 裡加上 
<script></script> 
1 2 3 4 5 6 7 8
   | <html> <head></head> <body>     <div>Hello {{.name}}</div>     <div>{{.someStr}}</div> </body> <script src="/js/index.js"></script> </html>
   | 
 
- 若是想要直接讀取 
./static/ 底下的文件,可以用 StripPrefix 將前綴 /js/ 過濾 
1
   | http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("./static"))))
  | 
 
結果
