您现在的位置是:首页 > 博客日记 > GoLang GoLang

go项目中生成静态文件(真静态)

2019-09-18 23:51:19

主方法

  1. var (
  2. datalist []map[string]string = make([]map[string]string, 0) //数据对象
  3. html_out_path = "./views/template/" //生成的HTML保存目录
  4. template_path = "./views/" //模板HTML目录
  5. temp_data_file = "./test_data.txt" //数据文件
  6. )
  7. func GenerateHtml() {
  8. //无数据库,加载数据
  9. //loadData()
  10. //重新生成前要先删除
  11. clearOldHtml()
  12. //生成静态HTML
  13. generateHtml()
  14. }
  15. func clearOldHtml() {
  16. //删除垃圾文件
  17. err := os.RemoveAll(html_out_path)
  18. if err != nil {
  19. log.Panicln(err.Error())
  20. }
  21. //新建目录
  22. err = os.MkdirAll(html_out_path, 0x644)
  23. if err != nil {
  24. log.Panicln(err.Error())
  25. }
  26. }
  27. func generateHtml() {
  28. //生成内容页面
  29. content_tmp, err := template.ParseFiles(filepath.Join(template_path, "index.tpl"))
  30. if err != nil {
  31. log.Panicln(err.Error())
  32. }
  33. data := make(map[string]string)
  34. filename := filepath.Join(html_out_path, fmt.Sprintf("index.html"))
  35. data["Website"] = "beego.me222"
  36. data["Email"] = "astaxie@gmail.com"
  37. generateStaticHtml(content_tmp, filename, data)
  38. }
  39. func generateStaticHtml(tmplate *template.Template, filename string, data map[string]string) {
  40. if IsExist(filename) {
  41. err := os.Remove(filename)
  42. if err != nil {
  43. log.Panicln(err.Error())
  44. }
  45. }
  46. file, err := os.OpenFile(filename, os.O_CREATE, 0x644)
  47. if err != nil {
  48. log.Panicln(err.Error())
  49. }
  50. defer file.Close()
  51. _ = tmplate.Execute(file, data)
  52. }
  53. //从数据文件中读入数据到datalist对象
  54. func loadData() {
  55. data, err := ioutil.ReadFile(temp_data_file)
  56. if err != nil {
  57. log.Panicln(err.Error())
  58. }
  59. arrline := strings.Split(strings.Trim(string(data), "\r\n "), "\r\n")
  60. for _, oneline := range arrline {
  61. sp_index := strings.Index(oneline, ";")
  62. if sp_index <= 0 {
  63. continue
  64. }
  65. append_data := make(map[string]string)
  66. append_data["title"] = oneline[:sp_index]
  67. append_data["content"] = oneline[sp_index+1:]
  68. datalist = append(datalist, append_data)
  69. }
  70. }
  71. /*
  72. 判断文件是否存在
  73. */
  74. func IsExist(file string) bool {
  75. _, err := os.Stat(file)
  76. return err == nil || os.IsExist(err)
  77. }

控制器使用

  1. exist := service.IsExist("views/template/index.html")
  2. if exist == false {
  3. service.GenerateHtml()
  4. c.Data["Website"] = "beego.me"
  5. c.Data["Email"] = "astaxie@gmail.com"
  6. c.TplName = "index.tpl"
  7. }else {
  8. c.TplExt = "html"
  9. c.TplName = "template/index.html"
  10. }


关注TinyMeng博客,更多精彩分享,敬请期待!