golang 缓存模版的方法

这是官方使用的方法,实例初始化时把所有模版渲染后缓存到 templates,后续使用ExecuteTemplate 方法来使用特定的模版

golang 缓存模版的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var templates = template.Must(template.ParseFiles("edit.html", "view.html"))

func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    err := templates.ExecuteTemplate(w, tmpl+".html", p)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func viewHandler(w http.ResponseWriter, r *http.Request) {
    title, err := getTitle(w, r)
    if err != nil {
        return
    }
    p, err := loadPage(title)
    if err != nil {
        http.Redirect(w, r, "/edit/"+title, http.StatusFound)
        return
    }
    renderTemplate(w, "view", p)
}

本文网址: https://pylist.com/topic/88.html 转摘请注明来源

Suggested Topics

一个简单高效的LRU 缓存golang 实现

LRU(Least recently used,最近最少使用)是根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。...

Golang 版 supervisord 使用记录

python 版经常出现一些错误,比如 supervisor.sock 文件找不到的错误。懒得去整,试试二进制的 supervisord ,用 Go 语言编写。...

Golang 服务之坑:too many open files

出现这个问题是因为服务的文件句柄超出系统限制。当Go服务程序出现这个问题,首先应该看系统设置,然后再看程序本身。...

使用Golang selenium WebDriver 自动登录微博

有时候在Golang 程序里需要读取微博的某个页面内容,提示需要登录。最简单的方法是在浏览器里登录后,直接复制Cookie 的内容,然后 http 请求带上Cookie。这样会有人工介入,不是很方便,这里借用 selenium WebDriver 来打开微博登录页面,然后自动填入用户名与密码。...

Golang 实现新闻网页提取正文内容

前段时间接触到新闻页面的提取问题,发现了python 实现的 gne ,测试一段时间,效果很好,但还不适合个人的需求,于是就用 go 来实现类似的功能。...

Leave a Comment