gpt4 book ai didi

templates - Go HTML 模板中的自动 Assets 修订文件名

转载 作者:IT王子 更新时间:2023-10-29 01:42:23 24 4
gpt4 key购买 nike

我正在寻求帮助,以实现在 Go HTML 模板中自动包含版本化文件名的功能。例如,在我的模板中,头部有这样的内容:

<link rel="stylesheet" href="{{ .MyCssFile }}" />

样式表本身有一大块 MD5 散列附加到名称上,来自名为 gulp-rev 的 gulp 脚本

stylesheet-d861367de2.css

目的是确保浏览器能够获取新的更改,同时也允许缓存。下面是 Django 中的示例实现,以便更好地解释:

https://docs.djangoproject.com/en/1.9/ref/contrib/staticfiles/#manifeststaticfilesstorage

A subclass of the StaticFilesStorage storage backend which stores the file names it handles by appending the MD5 hash of the file’s content to the filename. For example, the file css/styles.css would also be saved as css/styles.55e7cbb9ba48.css.

The purpose of this storage is to keep serving the old files in case some pages still refer to those files, e.g. because they are cached by you or a 3rd party proxy server. Additionally, it’s very helpful if you want to apply far future Expires headers to the deployed files to speed up the load time for subsequent page visits.

现在我想知道如何在 Go 中最好地实现这一点?我打算提供来自内置 file server 的文件.

我目前的想法是:

  • 有一个循环来检查目录中的最新样式表文件。听起来很慢。
  • 对通用命名文件进行某种重定向/重写(如 file.css 是根据对 file-hash.css 的请求提供的)。
  • 让 Go 自行管理 Assets 命名,附加哈希或时间戳。
  • 也许用 nginx 或其他东西更好地处理它?<​​/li>

最佳答案

写一个template function来解析名称。这是一个示例模板函数:

func resolveName(p string) (string, error) {
i := strings.LastIndex(p, ".")
if i < 0 {
i = len(p)
}
g := p[:i] + "-*" + p[i:]
matches, err := filepath.Glob(g)
if err != nil {
return "", err
}
if len(matches) != 1 {
return "", fmt.Errorf("%d matches for %s", len(matches), p)
}
return matches[0], nil
}

下面是注册为函数“resolveName”时如何在模板中使用它:

<link rel="stylesheet" href="{{ .MyCssFile | resolveName }}" />

playground example

此函数会在每次呈现模板时解析文件名。一个更聪明的函数可能会在解析名称时缓存名称,或者在启动时遍历目录树以预先构建缓存。

关于templates - Go HTML 模板中的自动 Assets 修订文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34558551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com