golang實現(xiàn)頁面靜態(tài)化操作的示例代碼
什么是頁面靜態(tài)化:
簡單的說,我們?nèi)绻L問一個鏈接 ,服務器對應的模塊會處理這個請求,轉(zhuǎn)到對應的go方法,最后生成我們想要看到的數(shù)據(jù)。這其中的缺點是顯而易見的:因為每次請求服務器都會進行處理,如 果有太多的高并發(fā)請求,那么就會加重應用服務器的壓力,弄不好就把服務器 搞down 掉了。那么如何去避免呢?如果我們把請求后的結(jié)果保存成一個 html 文件,然后每次用戶都去訪問 ,這樣應用服務器的壓力不就減少了?
那么靜態(tài)頁面從哪里來呢?總不能讓我們每個頁面都手動處理吧?這里就牽涉到我們要講解的內(nèi)容了,靜態(tài)頁面生成方案… 我們需要的是自動的生成靜態(tài)頁面,當用戶訪問 ,會自動生成html文件 ,然后顯示給用戶。
為了路由方便我用的gin框架但是不管用在什么框架上面都是一樣的
項目目錄:
project
-tem
--index.html
-main.go
main.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"`
}
//模擬從數(shù)據(jù)庫查詢過來的消息
var allproduct []*Product = []*Product{
{1, "蘋果手機"},
{2, "蘋果電腦"},
{3, "蘋果耳機"},
}
var (
//生成的Html保存目錄
htmlOutPath = "./tem"
//靜態(tài)文件模版目錄
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()
}
//生成靜態(tài)文件的方法
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.生成靜態(tài)文件
generateStaticHtml(contenstTmp, fileName, gin.H{"allproduct": allproduct})
}
//生成靜態(tài)文件
func generateStaticHtml(template *template.Template, fileName string, product map[string]interface{}) {
//1.判斷靜態(tài)文件是否存在
if exist(fileName) {
err := os.Remove(fileName)
if err != nil {
fmt.Println("移除文件失敗")
}
}
//2.生成靜態(tài)文件
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文件代碼:
{{define "index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>商品列表頁</title>
</head>
<tbody>
<div><a href="#" rel="external nofollow" >商品列表頁</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}}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
如何將Golang數(shù)組slice轉(zhuǎn)為逗號分隔的string字符串
這篇文章主要介紹了如何將Golang數(shù)組slice轉(zhuǎn)為逗號分隔的string字符串問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
go?doudou開發(fā)gRPC服務快速上手實現(xiàn)詳解
這篇文章主要為大家介紹了go?doudou開發(fā)gRPC服務快速上手實現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
Go 1.21新增的slices包中切片函數(shù)用法詳解
Go 1.21新增的 slices 包提供了很多和切片相關(guān)的函數(shù),可以用于任何類型的切片,本文通過代碼示例為大家介紹了部分切片函數(shù)的具體用法,感興趣的小伙伴可以了解一下2023-08-08

