Golang 页面静态化
不多bb,直接上代码。
项目结构
main包代码
package main
import (
"fmt"
"os"
"path/filepath"
"strconv"
"text/template"
"time"
)
type News struct {
Id int `json:"id"`
Auth string `json:"auth"`
Title string `json:"title"`
Date string `json:"date"`
Content string `json:"content"`
}
//定义一个chanel
var NewsChan = make(chan News, 1000)
var (
htmlOutPath = "./tem/news"
templatePath = "./tem"
)
func main() {
for i := 0; i < 5; i++ {
go webStatic(i)
}
//测试数据 生产环境可以结合定时任务从数据库定时拉取数据(每次取1000条)
for i := 0; i < 10; i++ {
news := News{
Id: i,
Auth: "xly",
Title: "上证A股",
Date: "2021-05-13",
Content: "今天又是个拉跨的日子",
}
NewsChan <- news
time.Sleep(1 * time.Second)
}
time.Sleep(20 * time.Second)
}
func webStatic(i int) {
for {
select {
case news := <-NewsChan:
if news.Id > 0 {
fmt.Println("第" + strconv.Itoa(i) + "协程执行静态化任务")
getNewsHtml(news)
} else {
fmt.Println("正在等待")
}
}
}
}
//生成静态文件的方法
func getNewsHtml(news News) {
//1.获取模版
dir, _ := os.Getwd()
fmt.Println(dir)
constTmp, err := template.ParseFiles(dir + "/static_web/index.html")
if err != nil {
fmt.Println("获取模版文件失败")
}
//2.获取html生成路径
fileName := filepath.Join(dir+"/static_web/"+htmlOutPath, strconv.Itoa(news.Id)+".html")
//4.生成静态文件
newsStaticHtml(constTmp, fileName, news)
}
//生成静态文件
func newsStaticHtml(template *template.Template, fileName string, news News) {
//1.判断静态文件是否存在
if exist(fileName) {
err := os.Remove(fileName)
if err != nil {
fmt.Println("移除文件失败")
}
}
//2.生成静态文件
file, err := os.Create(fileName)
if err != nil {
fmt.Println("生成文件失败")
}
defer file.Close()
template.Execute(file, news)
}
//判断文件是否存在
func exist(fileName string) bool {
_, err := os.Stat(fileName)
return err == nil || os.IsExist(err)
}
//静态模板文件index.html 代码
{{define "index.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>财经新闻</title>
</head>
<tbody>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>文章名称</th>
<th>文章作者</th>
<th>文章内容</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{.Id}}</td>
<td>{{.Title}}</td>
<td>{{.Auth}}</td>
<td>{{.Content}}</td>
</tr>
</tbody>
</table>
</html>
{{end}}
//实际效果图