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

主方法

var (
    datalist       []map[string]string = make([]map[string]string, 0) //数据对象
    html_out_path                      = "./views/template/"        //生成的HTML保存目录
    template_path                      = "./views/"                //模板HTML目录
    temp_data_file                     = "./test_data.txt"            //数据文件
)

func GenerateHtml() {
    //无数据库,加载数据
    //loadData()
    //重新生成前要先删除
    clearOldHtml()
    //生成静态HTML
    generateHtml()
}

func clearOldHtml() {
    //删除垃圾文件
    err := os.RemoveAll(html_out_path)
    if err != nil {
        log.Panicln(err.Error())
    }
    //新建目录
    err = os.MkdirAll(html_out_path, 0x644)
    if err != nil {
        log.Panicln(err.Error())
    }
}

func generateHtml() {
    //生成内容页面
    content_tmp, err := template.ParseFiles(filepath.Join(template_path, "index.tpl"))
    if err != nil {
        log.Panicln(err.Error())
    }
    data := make(map[string]string)
    filename := filepath.Join(html_out_path, fmt.Sprintf("index.html"))
    data["Website"] = "beego.me222"
    data["Email"] = "astaxie@gmail.com"
    generateStaticHtml(content_tmp, filename, data)
}

func generateStaticHtml(tmplate *template.Template, filename string, data map[string]string) {
    if IsExist(filename) {
        err := os.Remove(filename)
        if err != nil {
            log.Panicln(err.Error())
        }
    }
    file, err := os.OpenFile(filename, os.O_CREATE, 0x644)
    if err != nil {
        log.Panicln(err.Error())
    }
    defer file.Close()
    _ = tmplate.Execute(file, data)
}

//从数据文件中读入数据到datalist对象
func loadData() {
    data, err := ioutil.ReadFile(temp_data_file)
    if err != nil {
        log.Panicln(err.Error())
    }

    arrline := strings.Split(strings.Trim(string(data), "\r\n "), "\r\n")
    for _, oneline := range arrline {
        sp_index := strings.Index(oneline, ";")
        if sp_index <= 0 {
            continue
        }
        append_data := make(map[string]string)
        append_data["title"] = oneline[:sp_index]
        append_data["content"] = oneline[sp_index+1:]
        datalist = append(datalist, append_data)
    }
}

/*
判断文件是否存在
*/
func IsExist(file string) bool {
    _, err := os.Stat(file)
    return err == nil || os.IsExist(err)
}

控制器使用

exist := service.IsExist("views/template/index.html")
    if exist == false {
        service.GenerateHtml()
        c.Data["Website"] = "beego.me"
        c.Data["Email"] = "astaxie@gmail.com"
        c.TplName = "index.tpl"
    }else {
        c.TplExt = "html"
        c.TplName = "template/index.html"
    }
Last modification:September 18th, 2019 at 10:38 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment