溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

golang實(shí)現(xiàn)頁面靜態(tài)化操作的示例代碼

發(fā)布時(shí)間:2020-09-12 05:46:33 來源:腳本之家 閱讀:162 作者:lu569368 欄目:編程語言

什么是頁面靜態(tài)化:

簡(jiǎn)單的說,我們?nèi)绻L問一個(gè)鏈接 ,服務(wù)器對(duì)應(yīng)的模塊會(huì)處理這個(gè)請(qǐng)求,轉(zhuǎn)到對(duì)應(yīng)的go方法,最后生成我們想要看到的數(shù)據(jù)。這其中的缺點(diǎn)是顯而易見的:因?yàn)槊看握?qǐng)求服務(wù)器都會(huì)進(jìn)行處理,如 果有太多的高并發(fā)請(qǐng)求,那么就會(huì)加重應(yīng)用服務(wù)器的壓力,弄不好就把服務(wù)器 搞down 掉了。那么如何去避免呢?如果我們把請(qǐng)求后的結(jié)果保存成一個(gè) html 文件,然后每次用戶都去訪問 ,這樣應(yīng)用服務(wù)器的壓力不就減少了?

那么靜態(tài)頁面從哪里來呢?總不能讓我們每個(gè)頁面都手動(dòng)處理吧?這里就牽涉到我們要講解的內(nèi)容了,靜態(tài)頁面生成方案… 我們需要的是自動(dòng)的生成靜態(tài)頁面,當(dāng)用戶訪問 ,會(huì)自動(dòng)生成html文件 ,然后顯示給用戶。

為了路由方便我用的gin框架但是不管用在什么框架上面都是一樣的

項(xiàng)目目錄:

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, "蘋果手機(jī)"},
  {2, "蘋果電腦"},
  {3, "蘋果耳機(jī)"},
}
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}}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI