HTTP中ETag语法及使用实战详解
<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、ETag 简介</li><ul class="second_class_ul"><li>1.1 ETag 是什么</li><li>1.2 ETag 的作用</li><li>1.3 ETag 的语法</li><li>1.4 ETag 的使用</li></ul><li>二、ETag 实战</li><ul class="second_class_ul"><li>2.1 创建 Koa 服务器</li><ul class="third_class_ul"><li>2.1.1 public/index.html</li><li>2.1.2 public/index.js</li></ul><li>2.2 ETag 和 If-None-Match</li><ul class="third_class_ul"><li>2.2.1 首次请求 — 请求报文</li><li>2.2.2 首次请求 — 响应报文</li><li>2.2.3 10s内 — 请求报文</li><li>2.2.4 10s内 — 响应信息(General)</li><li>2.2.5 10s内 — 响应信息(Response Headers)</li><li>2.2.6 10s后 — 请求报文</li><li>2.2.7 10s后 — 响应报文</li></ul></ul><li>三、如何生成 ETag</li><ul class="second_class_ul"></ul><li>四、ETag vs Last-Modified</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>一、ETag 简介</h2><div class="cros igoods"><div class="goodsin" data-img="https://img14.360buyimg.com/pop/jfs/t1/22821/5/19509/61334/6331cdb5E70d519e2/60267bc4b98e4f69.jpg" data-name="详解HTTP:协议基础与Go语言实现(图灵出品)" data-owner="京东自营" data-price="64.9" data-tgid="38" data-url="https://union-click.jd.com/jdc?e=&p=JF8BAMoJK1olXwUFU1xdCE4TBl8IGV4WWQYGUm4ZVxNJXF9RXh5UHw0cSgYYXBcIWDoXSQVJQwYAUV1ZCE8RHDZNRwYlVVF4AxUpUjR3axlAZR1PXmIYNicreEcbM2gNHF4dXwMBZF5eDkwXAmoIK2sVXDZQOobrvpOysnPcsdTA1ZEyVW5dD00eA2sJH1gUWg8EZF5VDHtUVypcWBhdbTYyV25tOEsnAF9WdVpGWwQCUVlcZhZDSjRRRRISMwYCUllVD0oSCl8KGloXXzYy"></div></div>
<p class="maodian"></p><h3>1.1 ETag 是什么</h3>
<p>ETag(Entity Tag)是万维网协议 HTTP 的一部分。它是 HTTP 协议提供的若干机制中的一种 Web 缓存验证机制,并且允许客户端进行缓存协商。这使得缓存变得更加高效,而且节省带宽。如果资源的内容没有发生改变,Web 服务器就不需要发送一个完整的响应。</p>
<p class="maodian"></p><h3>1.2 ETag 的作用</h3>
<p>ETag 是一个不透明的标识符,由 Web 服务器根据 URL 上的资源的特定版本而指定。如果 URL 上的资源内容改变,一个新的不一样的 ETag 就会被生成。ETag 可以看成是资源的指纹,它们能够被快速地比较,以确定两个版本的资源是否相同。<br />需要注意的是 ETag 的比较只对同一个 URL 有意义 —— 不同 URL 上资源的 ETag 值可能相同也可能不同。</p>
<p class="maodian"></p><h3>1.3 ETag 的语法</h3>
<div class="jb51code"><pre class="brush:bash;">ETag: W/"<etag_value>"
ETag: "<etag_value>"
</pre></div>
<ul><li><code>W/(可选)</code>:'W/'(大小写敏感) 表示使用弱验证器。弱验证器很容易生成,但不利于比较。强验证器是比较的理想选择,但很难有效地生成。相同资源的两个弱 Etag 值可能语义等同,但不是每个字节都相同。</li><li><code>"<etag_value>"</code>:实体标签唯一地表示所请求的资源。它们是位于双引号之间的 ASCII 字符串(如 “2c-1799c10ab70” )。没有明确指定生成 ETag 值的方法。通常是使用内容的散列、最后修改时间戳的哈希值或简单地使用版本号。比如,MDN 使用 wiki 内容的十六进制数字的哈希值。</li></ul>
<p class="maodian"></p><h3>1.4 ETag 的使用</h3>
<p>在大多数场景下,当一个 URL 被请求,Web 服务器会返回资源和其相应的 ETag 值,它会被放置在 HTTP 响应头的 ETag 字段中:</p>
<div class="jb51code"><pre class="brush:bash;">HTTP/1.1 200 OK
Content-Length: 44
Cache-Control: max-age=10
Content-Type: application/javascript; charset=utf-8
ETag: W/"2c-1799c10ab70"
</pre></div>
<p>然后,客户端可以决定是否缓存这个资源和它的 ETag。以后,如果客户端想再次请求相同的 URL,将会发送一个包含已保存的 ETag 和 If-None-Match 字段的请求。</p>
<div class="jb51code"><pre class="brush:bash;">GET /index.js HTTP/1.1
Host: localhost:3000
Connection: keep-alive
If-None-Match: W/"2c-1799c10ab70"
</pre></div>
<p>客户端请求之后,服务器可能会比较客户端的 ETag 和当前版本资源的 ETag。如果 ETag 值匹配,这就意味着资源没有改变,服务器便会发送回一个极短的响应,包含 HTTP “304 未修改” 的状态。304 状态码告诉客户端,它的缓存版本是最新的,可以直接使用它。</p>
<div class="jb51code"><pre class="brush:bash;">HTTP/1.1 304 Not Modified
Cache-Control: max-age=10
ETag: W/"2c-1799c10ab70"
Connection: keep-alive
</pre></div>
<p class="maodian"></p><h2>二、ETag 实战</h2>
<p class="maodian"></p><h3>2.1 创建 Koa 服务器</h3>
<p>了解完 ETag 相关知识后,基于 <code>koa</code>、<code>koa-conditional-get</code>、<code>koa-etag</code> 和 <code>koa-static</code> 这些库来介绍一下,在实际项目中如何利用 <code>ETag</code> 响应头和 <code>If-None-Match</code> 请求头实现资源的缓存控制。</p>
<div class="jb51code"><pre class="brush:js;">// server.js
const Koa = require("koa");
const path = require("path");
const serve = require("koa-static");
const etag = require("koa-etag");
const conditional = require("koa-conditional-get");
const app = new Koa();
app.use(conditional()); // 使用条件请求中间件
app.use(etag()); // 使用etag中间件
app.use( // 使用静态资源中间件
serve(path.join(__dirname, "/public"), {
maxage: 10 * 1000, // 设置缓存存储的最大周期,单位为秒
})
);
app.listen(3000, () => {
console.log("app starting at port 3000");
});
</pre></div>
<p>在以上代码中,使用了 koa-static 中间件来处理静态资源,这些资源被保存在 <code>public</code> 目录下。在该目录下,创建了 index.html 和 index.js 两个资源文件,文件中的内容分别如下所示:</p>
<p class="maodian"></p><h4>2.1.1 public/index.html</h4>
<div class="jb51code"><pre class="brush:xhtml;"><!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ETag 使用示例</title>
<script src="/index.js"></script>
</head>
<body>
<h3>ETag 使用示例</h3>
</body>
</html>
</pre></div>
<p class="maodian"></p><h4>2.1.2 public/index.js</h4>
<div class="jb51code"><pre class="brush:bash;">console.log("大家好");
</pre></div>
<p>在启动完服务器之后,打开 Chrome 开发者工具并切换到 Network 标签栏,然后在浏览器地址栏输入 http://localhost:3000/ 地址,接着多次访问该地址(地址栏多次回车)。下图是多次访问的结果:</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202303/2023030708565601.png" /></p>
<p class="maodian"></p><h3>2.2 ETag 和 If-None-Match</h3>
<p>下面以 index.js 为例,来分析上图中与之对应的 HTTP 报文。对于 index.html 文件,感兴趣的小伙伴可以自行分析一下。接下来先来分析首次请求 index.js 文件的报文:</p>
<p class="maodian"></p><h4>2.2.1 首次请求 — 请求报文</h4>
<div class="jb51code"><pre class="brush:bash;">GET /index.js HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
...
</pre></div>
<p></p>
<p class="maodian"></p><h4>2.2.2 首次请求 — 响应报文</h4>
<div class="jb51code"><pre class="brush:bash;">HTTP/1.1 200 OK
Content-Length: 44
Cache-Control: max-age=10
ETag: W/"2c-1799c10ab70"
...
</pre></div>
<p>在使用了 koa-static 和 koa-etag 中间件之后,index.js 文件首次请求的响应报文中会包含 <code>Cache-Control</code> 和 <code>ETag</code> 的字段信息。<br /><code>Cache-Control</code> 描述的是一个相对时间,在进行缓存命中的时候,都是利用客户端时间进行判断,所以相比较 <code>Expires</code>,<code>Cache-Control</code> 的缓存管理更有效,安全一些。</p>
<p class="maodian"></p><h4>2.2.3 10s内 — 请求报文</h4>
<div class="jb51code"><pre class="brush:bash;">GET /index.js HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
...
</pre></div>
<p class="maodian"></p><h4>2.2.4 10s内 — 响应信息(General)</h4>
<div class="jb51code"><pre class="brush:bash;">Request URL: http://localhost:3000/index.js
Request Method: GET
Status Code: 200 OK (from memory cache)
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin
</pre></div>
<p class="maodian"></p><h4>2.2.5 10s内 — 响应信息(Response Headers)</h4>
<div class="jb51code"><pre class="brush:bash;">Cache-Control: max-age=10
Connection: keep-alive
Content-Length: 44
ETag: W/"2c-1799c10ab70"
</pre></div>
<p>由于设置了 index.js 资源文件的最大缓存时间为 10s,所以在 10s 内浏览器会直接从缓存中读取文件的内容。需要注意的是,此时的状态码为:<code>Status Code: 200 OK (from memory cache)</code>。</p>
<p class="maodian"></p><h4>2.2.6 10s后 — 请求报文</h4>
<div class="jb51code"><pre class="brush:bash;">GET /index.js HTTP/1.1
Host: localhost:3000
Connection: keep-alive
If-None-Match: W/"2c-1799c10ab70"
Referer: http://localhost:3000/
...
</pre></div>
<p>因为 10s 之后,缓存已经过期了,而且在 <code>index.js</code> 文件首次请求的响应报文中也返回了 <code>ETag</code> 字段。所以此时浏览器会发起 <code>If-None-Match</code> 条件请求。这类请求可以用来验证缓存的有效性,省去不必要的控制手段。</p>
<p class="maodian"></p><h4>2.2.7 10s后 — 响应报文</h4>
<div class="jb51code"><pre class="brush:bash;">HTTP/1.1 304 Not Modified
Cache-Control: max-age=10
ETag: W/"2c-1799c10ab70"
Connection: keep-alive
...
</pre></div>
<p>因为文件的内容未发生改变,所以 10s 后的响应报文的状态码为 304 Not Modified。此外,响应报文中也返回了 <code>ETag</code> 字段。看到这里,有一些小伙伴可能会有疑惑 —— ETag 到底是如何生成的?接下来揭开 <code>koa-etag</code> 中间件背后的秘密。</p>
<p class="maodian"></p><h2>三、如何生成 ETag</h2>
<p>在前面的示例中,使用了 koa-etag 中间件来实现资源的缓存控制。其实该中间件的实现并不复杂,具体如下所示:</p>
<div class="jb51code"><pre class="brush:js;">// https://github.com/koajs/etag/blob/master/index.js
const calculate = require('etag');
// 省略部分代码
module.exports = function etag (options) {
return async function etag (ctx, next) {
await next()
const entity = await getResponseEntity(ctx)
setEtag(ctx, entity, options)
}
}
</pre></div>
<p>由以上代码可知,在 <code>koa-etag</code> 中间件内部会先通过 <code>getResponseEntity</code> 函数来获取响应实体对象,然后再调用 <code>setETag</code> 函数来生成 ETag。而 <code>setETag</code> 函数的实现很简单,在 <code>setETag</code> 函数内部,会通过 <code>etag</code> 这个第三方库来生成 ETag。</p>
<div class="jb51code"><pre class="brush:js;">// https://github.com/koajs/etag/blob/master/index.js
function setEtag (ctx, entity, options) {
if (!entity) return
ctx.response.etag = calculate(entity, options)
}
</pre></div>
<p><code>etag</code> 这个库对外提供了一个 <code>etag</code> 函数来创建 ETag,该函数的签名如下:</p>
<div class="jb51code"><pre class="brush:js;">etag(entity, )
</pre></div>
<ul><li><code>entity</code>:用于生成 ETag 的实体,类型支持 <code>Strings</code>,<code>Buffers</code> 和 <code>fs.Stats</code>。除了 <code>fs.Stats</code> 对象之外,默认将生成 <code>strong ETag</code>。</li><li><code>options</code>:配置对象,支持通过 <code>options.weak</code> 属性来配置生成 weak ETag。</li></ul>
<p>了解完 <code>etag</code> 函数的参数之后,来看一下该函数的具体实现:</p>
<div class="jb51code"><pre class="brush:js;">function etag (entity, options) {
if (entity == null) {
throw new TypeError('argument entity is required')
}
// 支持fs.Stats对象
// isstats 函数的判断规则:当前对象是否包含ctime、mtime、ino和size这些属性
var isStats = isstats(entity)
var weak = options && typeof options.weak === 'boolean'
? options.weak
: isStats
// 参数校验
if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
}
// 生成ETag标签
var tag = isStats
? stattag(entity) // 处理fs.Stats对象
: entitytag(entity)
return weak
? 'W/' + tag
: tag
}
</pre></div>
<p>在 <code>etag</code> 函数内部会根据 <code>entity</code> 的类型,执行不同的生成逻辑。如果 <code>entity</code> 是 <code>fs.Stats</code> 对象,则会调用 <code>stattag</code> 函数来创建 ETag。</p>
<div class="jb51code"><pre class="brush:js;">function stattag (stat) {
// mtime:Modified Time,是在写入文件时随文件内容的更改而更改,是指文件内容最后一次被修改的时间。
var mtime = stat.mtime.getTime().toString(16)
var size = stat.size.toString(16)
return '"' + size + '-' + mtime + '"'
}
</pre></div>
<p>而如果 <code>entity</code> 参数非 <code>fs.Stats</code> 对象,则会调用 <code>entitytag</code> 函数来生成 ETag。其中 <code>entitytag</code> 函数的具体实现如下:</p>
<div class="jb51code"><pre class="brush:js;">function entitytag (entity) {
if (entity.length === 0) {
return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
}
// 计算实体对象的哈希值
var hash = crypto
.createHash('sha1')
.update(entity, 'utf8')
.digest('base64')
.substring(0, 27)
// 计算实体对象的长度
var len = typeof entity === 'string'
? Buffer.byteLength(entity, 'utf8')
: entity.length
return '"' + len.toString(16) + '-' + hash + '"'
}
</pre></div>
<p>对于非 <code>fs.Stats</code> 对象来说,在 <code>entitytag</code> 函数内部会使用 <code>sha1</code> 消息摘要算法来生成 <code>hash</code> 值并以 <code>base64</code> 格式输出,而实际的生成的 <code>hash</code> 值会取前 27 个字符。此外,由以上代码可知,最终的 ETag 将由实体的长度和哈希值两部分组成。<br />需要注意的是,生成 <code>ETag</code> 的算法并不是固定的, 通常是使用内容的散列、最后修改时间戳的哈希值或简单地使用版本号。</p>
<p class="maodian"></p><h2>四、ETag vs Last-Modified</h2>
<p>其实除了 <code>ETag</code> 字段之外,大多数情况下,响应头中还会包含 <code>Last-Modified</code> 字段。它们之间的区别如下:</p>
<ul><li>精确度上,Etag 要优于 Last-Modified。Last-Modified 的时间单位是秒,如果某个文件在 1 秒内被改变多次,那么它们的 Last-Modified 并没有体现出来修改,但是 Etag 每次都会改变,从而确保了精度;此外,如果是负载均衡的服务器,各个服务器生成的 Last-Modified 也有可能不一致。</li><li>性能上,Etag 要逊于 Last-Modified,毕竟 Last-Modified 只需要记录时间,而 ETag 需要服务器通过消息摘要算法来计算出一个hash 值。</li><li>优先级上,在资源新鲜度校验时,服务器会优先考虑 Etag。即如果条件请求的请求头同时携带 If-<code>Modified-Since</code> 和 <code>If-None-Match</code> 字段,则会优先判断资源的 ETag 值是否发生变化。</li></ul>
<p>以上就是HTTP中ETag语法及使用实战详解的详细内容,更多关于HTTP ETag语法的资料请关注琼殿技术社区其它相关文章!</p>
<div class="art_xg">
<b>您可能感兴趣的文章:</b><ul><li>HTTP缓存头Last-Modified和ETag介绍</li><li>Http 1.1 Etag 与 Last-Modified提高php效率</li><li>Etag和Expires 性能调优</li><li>使用ETags减少Web应用带宽和负载</li><li>HTTP缓存之ETag使用经验及效果</li></ul>
</div>
</div>
<!--endmain-->
頁:
[1]