### 什么是頁面靜態化:
簡 單的說,我們如果訪問一個鏈接 ,服務器對應的模塊會處理這個請求,轉到對應的go方法,最后生成我們想要看到的數據。這其中的缺點是顯而易見的:因為每次請求服務器都會進行處理,如 果有太多的高并發請求,那么就會加重應用服務器的壓力,弄不好就把服務器 搞down 掉了。那么如何去避免呢?如果我們把請求后的結果保存成一個 html 文件,然后每次用戶都去訪問 ,這樣應用服務器的壓力不就減少了?
那么靜態頁面從哪里來呢?總不能讓我們每個頁面都手動處理吧?這里就牽涉到我們要講解的內容了,靜態頁面生成方案… 我們需要的是自動的生成靜態頁面,當用戶訪問 ,會自動生成html文件 ,然后顯示給用戶。
**為了路由方便我用的gin框架但是不管用在什么框架上面都是一樣的**
項目目錄:
project
-tem
--index.html
-main.go
main.go文件代碼:
```go
package main
import (
"fmt"
"net/http"
"os"
"path/filepath"
"text/template"
"github.com/gin-gonic/gin"
)
type Product struct {
Id int64 `json:"id"` //字段一定要大寫不然各種問題
Name string `json:"name"`
}
//模擬從數據庫查詢過來的消息
var allproduct []*Product = []*Product{
{1, "蘋果手機"},
{2, "蘋果電腦"},
{3, "蘋果耳機"},
}
var (
//生成的Html保存目錄
htmlOutPath = "./tem"
//靜態文件模版目錄
templatePath = "./tem"
)
func main() {
r := gin.Default()
r.LoadHTMLGlob("tem/*")
r.GET("/index", func(c *gin.Context) {
GetGenerateHtml()
c.HTML(http.StatusOK, "index.html", gin.H{"allproduct": allproduct})
})
r.GET("/index2", func(c *gin.Context) {
c.HTML(http.StatusOK, "htmlindex.html", gin.H{})
})
r.Run()
}
//生成靜態文件的方法
func GetGenerateHtml() {
//1.獲取模版
contenstTmp, err := template.ParseFiles(filepath.Join(templatePath, "index.html"))
if err != nil {
fmt.Println("獲取模版文件失敗")
}
//2.獲取html生成路徑
fileName := filepath.Join(htmlOutPath, "htmlindex.html")
//4.生成靜態文件
generateStaticHtml(contenstTmp, fileName, gin.H{"allproduct": allproduct})
}
//生成靜態文件
func generateStaticHtml(template *template.Template, fileName string, product map[string]interface{}) {
//1.判斷靜態文件是否存在
if exist(fileName) {
err := os.Remove(fileName)
if err != nil {
fmt.Println("移除文件失敗")
}
}
//2.生成靜態文件
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
fmt.Println("打開文件失敗")
}
defer file.Close()
template.Execute(file, &product)
}
//判斷文件是否存在
func exist(fileName string) bool {
_, err := os.Stat(fileName)
return err == nil || os.IsExist(err)
}
```
tem/index.html文件代碼:
```html
{{define "index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>商品列表頁</title>
</head>
<tbody>
<div><a href="#">商品列表頁</a></div>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>商品名稱</th>
</tr>
</thead>
<tbody>
{{range .allproduct}}
<tr>
<td>{{.Id}}</td>
<td>{{.Name}}</td>
</tr>
{{end}}
</tbody>
</table>
</html>
{{end}}
```