Go发起HTTP2.0请求流程分析(后篇)——标头压缩

{"type":"doc","content":[{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"来自公众号:新世界杂货铺"}]}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"阅读建议"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这是HTTP2.0系列的最后一篇,笔者推荐阅读顺序如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://xie.infoq.cn/article/6107cc8ccba566d1bcb4b2159","title":""},"content":[{"type":"text","text":"Go中的HTTP请求之——HTTP1.1请求流程分析"}]}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://xie.infoq.cn/article/cb50c604d02c1ad0863e6a6d9","title":""},"content":[{"type":"text","text":"Go发起HTTP2.0请求流程分析(前篇)"}]}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://xie.infoq.cn/article/d4c93658b5760c35d44ad0678","title":""},"content":[{"type":"text","text":"Go发起HTTP2.0请求流程分析(中篇)——数据帧&流控制"}]}]}]}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"回顾"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在前篇"},{"type":"codeinline","content":[{"type":"text","text":"(*http2ClientConn).roundTrip"}]},{"type":"text","text":"方法中提到了写入请求header,而在写入请求header之前需要先编码(源码见https://github.com/golang/go/blob/master/src/net/http/h2_bundle.go#L7947)。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在中篇"},{"type":"codeinline","content":[{"type":"text","text":"(*http2ClientConn).readLoop"}]},{"type":"text","text":"方法中提到了"},{"type":"codeinline","content":[{"type":"text","text":"ReadFrame()"}]},{"type":"text","text":"方法,该方法会读取数据帧,如果是"},{"type":"codeinline","content":[{"type":"text","text":"http2FrameHeaders"}]},{"type":"text","text":"数据帧,会调用"},{"type":"codeinline","content":[{"type":"text","text":"(*http2Framer).readMetaFrame"}]},{"type":"text","text":"对读取到的数据帧解码(源码见https://github.com/golang/go/blob/master/src/net/http/h2_bundle.go#L2725)。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"因为标头压缩具有较高的独立性,所以笔者基于上面提到的编/解码部分的源码自己实现了一个可以独立运行的小例子。本篇将基于自己实现的例子进行标头压缩分析(完整例子见https://github.com/Isites/go-coder/blob/master/http2/hpack-example/main.go)。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"开门见山"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"HTTP2使用 HPACK 压缩格式压缩请求和响应标头元数据,这种格式采用下面两种技术压缩:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"通过静态哈夫曼代码对传输的标头字段进行编码,从而减小数据传输的大小。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"单个连接中,client和server共同维护一个相同的标头字段索引列表(笔者称为HPACK索引列表),此列表在之后的传输中用作编解码的参考。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"本篇不对哈夫曼编码做过多的阐述,主要对双端共同维护的索引列表进行分析。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"HPACK 压缩上下文包含一个静态表和一个动态表:静态表在规范中定义,并提供了一个包含所有连接都可能使用的常用 HTTP 标头字段的列表;动态表最初为空,将根据在特定连接内交换的值进行更新。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"HPACK索引列表"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"认识静/动态表需要先认识"},{"type":"codeinline","content":[{"type":"text","text":"headerFieldTable"}]},{"type":"text","text":"结构体,动态表和静态表都是基于它实现的。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"type headerFieldTable struct {\n\t// As in hpack, unique ids are 1-based. The unique id for ents[k] is k + evictCount + 1.\n\tents []HeaderField\n\tevictCount uint64\n\n\t// byName maps a HeaderField name to the unique id of the newest entry with the same name.\n\tbyName map[string]uint64\n\n\t// byNameValue maps a HeaderField name/value pair to the unique id of the newest\n\tbyNameValue map[pairNameValue]uint64\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面将对上述的字段分别进行描述:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"ents"}]},{"type":"text","text":":entries的缩写,代表着当前已经索引的Header数据。在headerFieldTable中,每一个Header都有一个唯一的Id,以"},{"type":"codeinline","content":[{"type":"text","text":"ents[k]"}]},{"type":"text","text":"为例,该唯一id的计算方式是"},{"type":"codeinline","content":[{"type":"text","text":"k + evictCount + 1"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"evictCount"}]},{"type":"text","text":":已经从ents中删除的条目数。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"byName"}]},{"type":"text","text":":存储具有相同Name的Header的唯一Id,最新Header的Name会覆盖老的唯一Id。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"byNameValue"}]},{"type":"text","text":":以Header的Name和Value为key存储对应的唯一Id。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"对字段的含义有所了解后,接下来对headerFieldTable几个比较重要的行为进行描述。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"},{"type":"strong"}],"text":"(*"},{"type":"text","marks":[{"type":"strong"}],"text":"headerFieldTable).addEntry"},{"type":"text","text":":添加Header实体到表中"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (t *headerFieldTable) addEntry(f HeaderField) {\n\tid := uint64(t.len()) + t.evictCount + 1\n\tt.byName[f.Name] = id\n\tt.byNameValue[pairNameValue{f.Name, f.Value}] = id\n\tt.ents = append(t.ents, f)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先,计算出Header在headerFieldTable中的唯一Id,并将其分别存入"},{"type":"codeinline","content":[{"type":"text","text":"byName"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"byNameValue"}]},{"type":"text","text":"中。最后,将Header存入"},{"type":"codeinline","content":[{"type":"text","text":"ents"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"因为使用了append函数,这意味着"},{"type":"codeinline","content":[{"type":"text","text":"ents[0]"}]},{"type":"text","text":"存储的是存活最久的Header。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"},{"type":"strong"}],"text":"(*"},{"type":"text","marks":[{"type":"strong"}],"text":"headerFieldTable).evictOldest"},{"type":"text","text":":从表中删除指定个数的Header实体"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (t *headerFieldTable) evictOldest(n int) {\n\tif n > t.len() {\n\t\tpanic(fmt.Sprintf(\"evictOldest(%v) on table with %v entries\", n, t.len()))\n\t}\n\tfor k := 0; k < n; k++ {\n\t\tf := t.ents[k]\n\t\tid := t.evictCount + uint64(k) + 1\n\t\tif t.byName[f.Name] == id {\n\t\t\tdelete(t.byName, f.Name)\n\t\t}\n\t\tif p := (pairNameValue{f.Name, f.Value}); t.byNameValue[p] == id {\n\t\t\tdelete(t.byNameValue, p)\n\t\t}\n\t}\n\tcopy(t.ents, t.ents[n:])\n\tfor k := t.len() - n; k < t.len(); k++ {\n\t\tt.ents[k] = HeaderField{} // so strings can be garbage collected\n\t}\n\tt.ents = t.ents[:t.len()-n]\n\tif t.evictCount+uint64(n) < t.evictCount {\n\t\tpanic(\"evictCount overflow\")\n\t}\n\tt.evictCount += uint64(n)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"第一个for循环的下标是从0开始的,也就是说删除Header时遵循先进先出的原则。删除Header的步骤如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"删除"},{"type":"codeinline","content":[{"type":"text","text":"byName"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"byNameValue"}]},{"type":"text","text":"的映射。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"将第n位及其之后的Header前移。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"将倒数的n个Header置空,以方便垃圾回收。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"改变ents的长度。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":5,"align":null,"origin":null},"content":[{"type":"text","text":"增加"},{"type":"codeinline","content":[{"type":"text","text":"evictCount"}]},{"type":"text","text":"的数量。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"},{"type":"strong"}],"text":"(*"},{"type":"text","marks":[{"type":"strong"}],"text":"headerFieldTable).search"},{"type":"text","text":":从当前表中搜索指定Header并返回在当前表中的Index(此处的"},{"type":"codeinline","content":[{"type":"text","text":"Index"}]},{"type":"text","text":"和切片中的下标含义是不一样的)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (t *headerFieldTable) search(f HeaderField) (i uint64, nameValueMatch bool) {\n\tif !f.Sensitive {\n\t\tif id := t.byNameValue[pairNameValue{f.Name, f.Value}]; id != 0 {\n\t\t\treturn t.idToIndex(id), true\n\t\t}\n\t}\n\tif id := t.byName[f.Name]; id != 0 {\n\t\treturn t.idToIndex(id), false\n\t}\n\treturn 0, false\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果Header的Name和Value均匹配,则返回当前表中的Index且"},{"type":"codeinline","content":[{"type":"text","text":"nameValueMatch"}]},{"type":"text","text":"为true。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果仅有Header的Name匹配,则返回当前表中的Index且"},{"type":"codeinline","content":[{"type":"text","text":"nameValueMatch"}]},{"type":"text","text":"为false。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果Header的Name和Value均不匹配,则返回0且"},{"type":"codeinline","content":[{"type":"text","text":"nameValueMatch"}]},{"type":"text","text":"为false。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"},{"type":"strong"}],"text":"(*"},{"type":"text","marks":[{"type":"strong"}],"text":"headerFieldTable).idToIndex"},{"type":"text","text":":通过当前表中的唯一Id计算出当前表对应的Index"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (t *headerFieldTable) idToIndex(id uint64) uint64 {\n\tif id <= t.evictCount {\n\t\tpanic(fmt.Sprintf(\"id (%v) <= evictCount (%v)\", id, t.evictCount))\n\t}\n\tk := id - t.evictCount - 1 // convert id to an index t.ents[k]\n\tif t != staticTable {\n\t\treturn uint64(t.len()) - k // dynamic table\n\t}\n\treturn k + 1\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"静态表:"},{"type":"codeinline","content":[{"type":"text","text":"Index"}]},{"type":"text","text":"从1开始,且Index为1时对应的元素为"},{"type":"codeinline","content":[{"type":"text","text":"t.ents[0]"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"动态表: "},{"type":"codeinline","content":[{"type":"text","text":"Index"}]},{"type":"text","text":"也从1开始,但是Index为1时对应的元素为"},{"type":"codeinline","content":[{"type":"text","text":"t.ents[t.len()-1]"}]},{"type":"text","text":"。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"静态表"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"静态表中包含了一些每个连接都可能使用到的Header。其实现如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"var staticTable = newStaticTable()\nfunc newStaticTable() *headerFieldTable {\n\tt := &headerFieldTable{}\n\tt.init()\n\tfor _, e := range staticTableEntries[:] {\n\t\tt.addEntry(e)\n\t}\n\treturn t\n}\nvar staticTableEntries = [...]HeaderField{\n\t{Name: \":authority\"},\n\t{Name: \":method\", Value: \"GET\"},\n\t{Name: \":method\", Value: \"POST\"},\n // 此处省略代码\n\t{Name: \"www-authenticate\"},\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面的"},{"type":"codeinline","content":[{"type":"text","text":"t.init"}]},{"type":"text","text":"函数仅做初始化"},{"type":"codeinline","content":[{"type":"text","text":"t.byName"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"t.byNameValue"}]},{"type":"text","text":"用。笔者在这里仅展示了部分预定义的Header,完整预定义Header参见https://github.com/golang/go/blob/master/src/vendor/golang.org/x/net/http2/hpack/tables.go#L130。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"动态表"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"动态表结构体如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"type dynamicTable struct {\n\t// http://http2.github.io/http2-spec/compression.html#rfc.section.2.3.2\n\ttable headerFieldTable\n\tsize uint32 // in bytes\n\tmaxSize uint32 // current maxSize\n\tallowedMaxSize uint32 // maxSize may go up to this, inclusive\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"动态表的实现是基于"},{"type":"codeinline","content":[{"type":"text","text":"headerFieldTable"}]},{"type":"text","text":",相比原先的基础功能增加了表的大小限制,其他功能保持不变。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"静态表和动态表构成完整的HPACK索引列表"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"前面介绍了动/静态表中内部的Index和内部的唯一Id,而在一次连接中HPACK索引列表是由静态表和动态表一起构成,那此时在连接中的HPACK索引是怎么样的呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"带着这样的疑问我们看看下面的结构:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/7a/7a06c96380231681b43fc4b6d8f35f99.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上图中蓝色部分表示静态表,黄色部分表示动态表。\t"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"H1...Hn"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"H1...Hm"}]},{"type":"text","text":"分别表示存储在静态表和动态表中的Header元素。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"在HPACK索引中静态表部分的索引和静态表的内部索引保持一致,动态表部分的索引为动态表内部索引加上静态表索引的最大值"},{"type":"text","text":"。在一次连接中Client和Server通过HPACK索引标识唯一的Header元素。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"HPACK编码"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"众所周知HTTP2的标头压缩能够减少很多数据的传输,接下来我们通过下面的例子,对比一下编码前后的数据大小:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"var (\n buf bytes.Buffer\n oriSize int\n)\nhenc := hpack.NewEncoder(&buf)\nheaders := []hpack.HeaderField{\n {Name: \":authority\", Value: \"dss0.bdstatic.com\"},\n {Name: \":method\", Value: \"GET\"},\n {Name: \":path\", Value: \"/5aV1bjqh_Q23odCf/static/superman/img/topnav/[email protected]\"},\n {Name: \":scheme\", Value: \"https\"},\n {Name: \"accept-encoding\", Value: \"gzip\"},\n {Name: \"user-agent\", Value: \"Go-http-client/2.0\"},\n {Name: \"custom-header\", Value: \"custom-value\"},\n}\nfor _, header := range headers {\n oriSize += len(header.Name) + len(header.Value)\n henc.WriteField(header)\n}\nfmt.Printf(\"ori size: %v, encoded size: %v\\n\", oriSize, buf.Len())\n//输出为:ori size: 197, encoded size: 111"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"注:在 HTTP2 中,请求和响应标头字段的定义保持不变,仅有一些微小的差异:所有标头字段名称均为小写,请求行现在拆分成各个 "},{"type":"codeinline","content":[{"type":"text","text":":method"}]},{"type":"text","text":"、"},{"type":"codeinline","content":[{"type":"text","text":":scheme"}]},{"type":"text","text":"、"},{"type":"codeinline","content":[{"type":"text","text":":authority"}]},{"type":"text","text":" 和 "},{"type":"codeinline","content":[{"type":"text","text":":path"}]},{"type":"text","text":" 伪标头字段。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在上面的例子中,我们看到原来为197字节的标头数据现在只有111字节,减少了近一半的数据量!"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"带着一种 “卧槽,牛逼!”的心情开始对"},{"type":"codeinline","content":[{"type":"text","text":"henc.WriteField"}]},{"type":"text","text":"方法调试。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (e *Encoder) WriteField(f HeaderField) error {\n\te.buf = e.buf[:0]\n\n\tif e.tableSizeUpdate {\n\t\te.tableSizeUpdate = false\n\t\tif e.minSize < e.dynTab.maxSize {\n\t\t\te.buf = appendTableSize(e.buf, e.minSize)\n\t\t}\n\t\te.minSize = uint32Max\n\t\te.buf = appendTableSize(e.buf, e.dynTab.maxSize)\n\t}\n\n\tidx, nameValueMatch := e.searchTable(f)\n\tif nameValueMatch {\n\t\te.buf = appendIndexed(e.buf, idx)\n\t} else {\n\t\tindexing := e.shouldIndex(f)\n\t\tif indexing {\n\t\t\te.dynTab.add(f) // 加入动态表中\n\t\t}\n\n\t\tif idx == 0 {\n\t\t\te.buf = appendNewName(e.buf, f, indexing)\n\t\t} else {\n\t\t\te.buf = appendIndexedName(e.buf, f, idx, indexing)\n\t\t}\n\t}\n\tn, err := e.w.Write(e.buf)\n\tif err == nil && n != len(e.buf) {\n\t\terr = io.ErrShortWrite\n\t}\n\treturn err\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"经调试发现,本例中"},{"type":"codeinline","content":[{"type":"text","text":":authority"}]},{"type":"text","text":","},{"type":"codeinline","content":[{"type":"text","text":":path"}]},{"type":"text","text":","},{"type":"codeinline","content":[{"type":"text","text":"accept-encoding"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"user-agent"}]},{"type":"text","text":"走了"},{"type":"codeinline","content":[{"type":"text","text":"appendIndexedName"}]},{"type":"text","text":"分支;"},{"type":"codeinline","content":[{"type":"text","text":":method"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":":scheme"}]},{"type":"text","text":"走了"},{"type":"codeinline","content":[{"type":"text","text":"appendIndexed"}]},{"type":"text","text":"分支;"},{"type":"codeinline","content":[{"type":"text","text":"custom-header"}]},{"type":"text","text":"走了"},{"type":"codeinline","content":[{"type":"text","text":"appendNewName"}]},{"type":"text","text":"分支。这三种分支总共代表了两种不同的编码方法。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"由于本例中"},{"type":"codeinline","content":[{"type":"text","text":"f.Sensitive"}]},{"type":"text","text":"默认值为false且Encoder给动态表的默认大小为4096,按照"},{"type":"codeinline","content":[{"type":"text","text":"e.shouldIndex"}]},{"type":"text","text":"的逻辑本例中"},{"type":"codeinline","content":[{"type":"text","text":"indexing"}]},{"type":"text","text":"一直为true(在笔者所使用的go1.14.2源码中,client端尚未发现有使"},{"type":"codeinline","content":[{"type":"text","text":"f.Sensitive"}]},{"type":"text","text":"为true的代码)。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"笔者对上面"},{"type":"codeinline","content":[{"type":"text","text":"e.tableSizeUpdate"}]},{"type":"text","text":"相关的逻辑不提的原因是控制"},{"type":"codeinline","content":[{"type":"text","text":"e.tableSizeUpdate"}]},{"type":"text","text":"的方法为"},{"type":"codeinline","content":[{"type":"text","text":"e.SetMaxDynamicTableSizeLimit"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"e.SetMaxDynamicTableSize"}]},{"type":"text","text":",而笔者在"},{"type":"codeinline","content":[{"type":"text","text":"(*http2Transport).newClientConn"}]},{"type":"text","text":"(此方法相关逻辑参见前篇)相关的源码中发现了这样的注释:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"// TODO: SetMaxDynamicTableSize, SetMaxDynamicTableSizeLimit on\n// henc in response to SETTINGS frames?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"笔者看到这里的时候内心激动不已呀,产生了一种强烈的想贡献代码的欲望,奈何自己能力有限只能看着机会却抓不住呀,只好含恨埋头苦学(开个玩笑~,毕竟某位智者说过,写的越少BUG越少😄)。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"},{"type":"strong"}],"text":"(*"},{"type":"text","marks":[{"type":"strong"}],"text":"Encoder).searchTable"},{"type":"text","text":":从HPACK索引列表中搜索Header,并返回对应的索引。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (e *Encoder) searchTable(f HeaderField) (i uint64, nameValueMatch bool) {\n\ti, nameValueMatch = staticTable.search(f)\n\tif nameValueMatch {\n\t\treturn i, true\n\t}\n\n\tj, nameValueMatch := e.dynTab.table.search(f)\n\tif nameValueMatch || (i == 0 && j != 0) {\n\t\treturn j + uint64(staticTable.len()), nameValueMatch\n\t}\n\n\treturn i, false\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"搜索顺序为,先搜索静态表,如果静态表不匹配,则搜索动态表,最后返回。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"索引Header表示法"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"此表示法对应的函数为"},{"type":"text","marks":[{"type":"strong"}],"text":"appendIndexed"},{"type":"text","text":",且该Header已经在索引列表中。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"该函数将Header在HPACK索引列表中的索引编码,原先的Header最后仅用少量的几个字节就可以表示。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func appendIndexed(dst []byte, i uint64) []byte {\n\tfirst := len(dst)\n\tdst = appendVarInt(dst, 7, i)\n\tdst[first] |= 0x80\n\treturn dst\n}\nfunc appendVarInt(dst []byte, n byte, i uint64) []byte {\n\tk := uint64((1 << n) - 1)\n\tif i < k {\n\t\treturn append(dst, byte(i))\n\t}\n\tdst = append(dst, byte(k))\n\ti -= k\n\tfor ; i >= 128; i >>= 7 {\n\t\tdst = append(dst, byte(0x80|(i&0x7f)))\n\t}\n\treturn append(dst, byte(i))\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"由"},{"type":"codeinline","content":[{"type":"text","text":"appendIndexed"}]},{"type":"text","text":"知,用索引头字段表示法时,第一个字节的格式必须是"},{"type":"codeinline","content":[{"type":"text","text":"0b1xxxxxxx"}]},{"type":"text","text":",即第0位必须为"},{"type":"codeinline","content":[{"type":"text","text":"1"}]},{"type":"text","text":",低7位用来表示值。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果索引大于"},{"type":"codeinline","content":[{"type":"text","text":"uint64((1 << n) - 1)"}]},{"type":"text","text":"时,需要使用多个字节来存储索引的值,步骤如下:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"第一个字节的最低n位全为1。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"索引i减去uint64((1 << n) - 1)后,每次取低7位或上"},{"type":"codeinline","content":[{"type":"text","text":"0b10000000"}]},{"type":"text","text":", 然后i右移7位并和128进行比较,判断是否进入下一次循环。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"循环结束后将剩下的i值直接放入buf中。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用这种方法表示Header时,仅需要少量字节就可以表示一个完整的Header头字段,最好的情况是一个字节就可以表示一个Header字段。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"增加动态表Header表示法"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"此种表示法对应两种情况:一,Header的Name有匹配索引;二,Header的Name和Value均无匹配索引。这两种情况分别对应的处理函数为"},{"type":"codeinline","content":[{"type":"text","text":"appendIndexedName"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"appendNewName"}]},{"type":"text","text":"。这两种情况均会将Header添加到动态表中。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"appendIndexedName:"},{"type":"text","text":" 编码有Name匹配的Header字段。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func appendIndexedName(dst []byte, f HeaderField, i uint64, indexing bool) []byte {\n\tfirst := len(dst)\n\tvar n byte\n\tif indexing {\n\t\tn = 6\n\t} else {\n\t\tn = 4\n\t}\n\tdst = appendVarInt(dst, n, i)\n\tdst[first] |= encodeTypeByte(indexing, f.Sensitive)\n\treturn appendHpackString(dst, f.Value)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在这里我们先看看"},{"type":"codeinline","content":[{"type":"text","text":"encodeTypeByte"}]},{"type":"text","text":"函数:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func encodeTypeByte(indexing, sensitive bool) byte {\n\tif sensitive {\n\t\treturn 0x10\n\t}\n\tif indexing {\n\t\treturn 0x40\n\t}\n\treturn 0\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"前面提到本例中indexing一直为true,sensitive为false,所以encodeTypeByte的返回值一直为"},{"type":"codeinline","content":[{"type":"text","text":"0x40"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"此时回到appendIndexedName函数,我们知道增加动态表Header表示法的第一个字节格式必须是"},{"type":"codeinline","content":[{"type":"text","text":"0xb01xxxxxx"}]},{"type":"text","text":",即最高两位必须是"},{"type":"codeinline","content":[{"type":"text","text":"01"}]},{"type":"text","text":",低6位用于表示Header中Name的索引。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过"},{"type":"codeinline","content":[{"type":"text","text":"appendVarInt"}]},{"type":"text","text":"对索引编码后,下面我们看看"},{"type":"codeinline","content":[{"type":"text","text":"appendHpackString"}]},{"type":"text","text":"函数如何对Header的Value进行编码:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func appendHpackString(dst []byte, s string) []byte {\n\thuffmanLength := HuffmanEncodeLength(s)\n\tif huffmanLength < uint64(len(s)) {\n\t\tfirst := len(dst)\n\t\tdst = appendVarInt(dst, 7, huffmanLength)\n\t\tdst = AppendHuffmanString(dst, s)\n\t\tdst[first] |= 0x80\n\t} else {\n\t\tdst = appendVarInt(dst, 7, uint64(len(s)))\n\t\tdst = append(dst, s...)\n\t}\n\treturn dst\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"appendHpackString"}]},{"type":"text","text":"编码时分为两种情况:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"哈夫曼编码后的长度小于原Value的长度时,先用"},{"type":"codeinline","content":[{"type":"text","text":"appendVarInt"}]},{"type":"text","text":"将哈夫曼编码后的最终长度存入buf,然后再将真实的哈夫曼编码存入buf。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"哈夫曼编码后的长度大于等于原Value的长度时,先用"},{"type":"codeinline","content":[{"type":"text","text":"appendVarInt"}]},{"type":"text","text":"将原Value的长度存入buf,然后再将原Value存入buf。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在这里需要注意的是存储Value长度时仅用了字节的低7位,最高位为1表示存储的内容为哈夫曼编码,最高位为0表示存储的内容为原Value。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"appendNewName:"},{"type":"text","text":" 编码Name和Value均无匹配的Header字段。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func appendNewName(dst []byte, f HeaderField, indexing bool) []byte {\n\tdst = append(dst, encodeTypeByte(indexing, f.Sensitive))\n\tdst = appendHpackString(dst, f.Name)\n\treturn appendHpackString(dst, f.Value)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"前面提到"},{"type":"codeinline","content":[{"type":"text","text":"encodeTypeByte"}]},{"type":"text","text":"的返回值为"},{"type":"codeinline","content":[{"type":"text","text":"0x40"}]},{"type":"text","text":",所以我们此时编码的第一个字节为"},{"type":"codeinline","content":[{"type":"text","text":"0b01000000"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"第一个字节编码结束后通过"},{"type":"codeinline","content":[{"type":"text","text":"appendHpackString"}]},{"type":"text","text":"先后对Header的Name和Value进行编码。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"HPACK解码"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"前面理了一遍HPACK的编码过程,下面我们通过一个解码的例子来理一遍解码的过程。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"// 此处省略HPACK编码中的编码例子\nvar (\n invalid error\n sawRegular bool\n // 16 << 20 from fr.maxHeaderListSize() from\n remainSize uint32 = 16 << 20\n)\nhdec := hpack.NewDecoder(4096, nil)\n// 16 << 20 from fr.maxHeaderStringLen() from fr.maxHeaderListSize()\nhdec.SetMaxStringLength(int(remainSize))\nhdec.SetEmitFunc(func(hf hpack.HeaderField) {\n if !httpguts.ValidHeaderFieldValue(hf.Value) {\n invalid = fmt.Errorf(\"invalid header field value %q\", hf.Value)\n }\n isPseudo := strings.HasPrefix(hf.Name, \":\")\n if isPseudo {\n if sawRegular {\n invalid = errors.New(\"pseudo header field after regular\")\n }\n } else {\n sawRegular = true\n // if !http2validWireHeaderFieldName(hf.Name) {\n // \tinvliad = fmt.Sprintf(\"invalid header field name %q\", hf.Name)\n // }\n }\n if invalid != nil {\n fmt.Println(invalid)\n hdec.SetEmitEnabled(false)\n return\n }\n size := hf.Size()\n if size > remainSize {\n hdec.SetEmitEnabled(false)\n // mh.Truncated = true\n return\n }\n remainSize -= size\n fmt.Printf(\"%+v\\n\", hf)\n // mh.Fields = append(mh.Fields, hf)\n})\ndefer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})\nfmt.Println(hdec.Write(buf.Bytes()))\n// 输出如下:\n// ori size: 197, encoded size: 111\n// header field \":authority\" = \"dss0.bdstatic.com\"\n// header field \":method\" = \"GET\"\n// header field \":path\" = \"/5aV1bjqh_Q23odCf/static/superman/img/topnav/[email protected]\"\n// header field \":scheme\" = \"https\"\n// header field \"accept-encoding\" = \"gzip\"\n// header field \"user-agent\" = \"Go-http-client/2.0\"\n// header field \"custom-header\" = \"custom-value\"\n// 111 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过最后一行的输出可以知道确确实实从111个字节中解码出了197个字节的原Header数据。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"而这解码的过程笔者将从"},{"type":"codeinline","content":[{"type":"text","text":"hdec.Write"}]},{"type":"text","text":"方法开始分析,逐步揭开它的神秘面纱。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":" func (d *Decoder) Write(p []byte) (n int, err error) {\n // 此处省略代码\n\tif d.saveBuf.Len() == 0 {\n\t\td.buf = p\n\t} else {\n\t\td.saveBuf.Write(p)\n\t\td.buf = d.saveBuf.Bytes()\n\t\td.saveBuf.Reset()\n\t}\n\n\tfor len(d.buf) > 0 {\n\t\terr = d.parseHeaderFieldRepr()\n\t\tif err == errNeedMore {\n\t\t\t// 此处省略代码\n\t\t\td.saveBuf.Write(d.buf)\n\t\t\treturn len(p), nil\n\t\t}\n\t\t// 此处省略代码\n\t}\n\treturn len(p), err\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在笔者debug的过程中发现解码的核心逻辑主要在"},{"type":"codeinline","content":[{"type":"text","text":"d.parseHeaderFieldRepr"}]},{"type":"text","text":"方法里。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (d *Decoder) parseHeaderFieldRepr() error {\n\tb := d.buf[0]\n\tswitch {\n\tcase b&128 != 0:\n\t\treturn d.parseFieldIndexed()\n\tcase b&192 == 64:\n\t\treturn d.parseFieldLiteral(6, indexedTrue)\n // 此处省略代码\n\t}\n\treturn DecodingError{errors.New(\"invalid encoding\")}\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"第一个字节与上128不为0只有一种情况,那就是b为"},{"type":"codeinline","content":[{"type":"text","text":"0b1xxxxxxx"}]},{"type":"text","text":"格式的数据,综合前面的编码逻辑可以知道索引Header表示法对应的解码方法为"},{"type":"codeinline","content":[{"type":"text","text":"d.parseFieldIndexed"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"第一个字节与上192为64也只有一种情况,那就是b为"},{"type":"codeinline","content":[{"type":"text","text":"0b01xxxxxx"}]},{"type":"text","text":"格式的数据,综合前面的编码逻辑可以知道增加动态表Header表示法对应的解码方法为"},{"type":"codeinline","content":[{"type":"text","text":"d.parseFieldLiteral"}]},{"type":"text","text":"。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"索引Header表示法"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过"},{"type":"codeinline","content":[{"type":"text","text":"(*Decoder).parseFieldIndexed"}]},{"type":"text","text":"解码时,真实的Header数据已经在静态表或者动态表中了,只要通过HPACK索引找到对应的Header就解码成功了。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (d *Decoder) parseFieldIndexed() error {\n\tbuf := d.buf\n\tidx, buf, err := readVarInt(7, buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\thf, ok := d.at(idx)\n\tif !ok {\n\t\treturn DecodingError{InvalidIndexError(idx)}\n\t}\n\td.buf = buf\n\treturn d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value})\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上述方法主要有三个步骤:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"通过"},{"type":"codeinline","content":[{"type":"text","text":"readVarInt"}]},{"type":"text","text":"函数读取HPACK索引。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"通过"},{"type":"codeinline","content":[{"type":"text","text":"d.at"}]},{"type":"text","text":"方法找到索引列表中真实的Header数据。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"将Header传递给最上层。"},{"type":"codeinline","content":[{"type":"text","text":"d.CallEmit"}]},{"type":"text","text":"最终会调用"},{"type":"codeinline","content":[{"type":"text","text":"hdec.SetEmitFunc"}]},{"type":"text","text":"设置的闭包,从而将Header传递给最上层。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"readVarInt"},{"type":"text","text":":读取HPACK索引"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) {\n\tif n < 1 || n > 8 {\n\t\tpanic(\"bad n\")\n\t}\n\tif len(p) == 0 {\n\t\treturn 0, p, errNeedMore\n\t}\n\ti = uint64(p[0])\n\tif n < 8 {\n\t\ti &= (1 << uint64(n)) - 1\n\t}\n\tif i < (1< 0 {\n\t\tb := p[0]\n\t\tp = p[1:]\n\t\ti += uint64(b&127) << m\n\t\tif b&128 == 0 {\n\t\t\treturn i, p, nil\n\t\t}\n\t\tm += 7\n\t\tif m >= 63 { // TODO: proper overflow check. making this up.\n\t\t\treturn 0, origP, errVarintOverflow\n\t\t}\n\t}\n\treturn 0, origP, errNeedMore\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"由上述的readVarInt函数知,当第一个字节的低n为不全为1时,则低n为代表真实的HPACK索引,可以直接返回。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当第一个字节的低n为全为1时,需要读取更多的字节数来计算真正的HPACK索引。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"第一次循环时m为0,b的低7位加上"},{"type":"codeinline","content":[{"type":"text","text":"(1< uint64(d.maxTableIndex()) {\n\t\treturn\n\t}\n\tdt := d.dynTab.table\n\treturn dt.ents[dt.len()-(int(i)-staticTable.len())], true\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"索引小于静态表长度时,直接从静态表中获取Header数据。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"索引长度大于静态表时,根据前面介绍的"},{"type":"text","marks":[{"type":"strong"}],"text":"HPACK索引列表"},{"type":"text","text":",可以通过"},{"type":"codeinline","content":[{"type":"text","text":"dt.len()-(int(i)-staticTable.len())"}]},{"type":"text","text":"计算出i在动态表"},{"type":"codeinline","content":[{"type":"text","text":"ents"}]},{"type":"text","text":"的真实下标,从而获取Header数据。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"增加动态表Header表示法"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通过"},{"type":"codeinline","content":[{"type":"text","text":"(*Decoder).parseFieldLiteral"}]},{"type":"text","text":"解码时,需要考虑两种情况。一、Header的Name有索引。二、Header的Name和Value均无索引。这两种情况下,该Header都不存在于动态表中。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面分步骤分析"},{"type":"codeinline","content":[{"type":"text","text":"(*Decoder).parseFieldLiteral"}]},{"type":"text","text":"方法。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"1、读取buf中的HPACK索引。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"nameIdx, buf, err := readVarInt(n, buf)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"2、 如果索引不为0,则从HPACK索引列表中获取Header的Name。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"ihf, ok := d.at(nameIdx)\nif !ok {\n return DecodingError{InvalidIndexError(nameIdx)}\n}\nhf.Name = ihf.Name"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"3、如果索引为0,则从buf中读取Header的Name。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"hf.Name, buf, err = d.readString(buf, wantStr)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"4、从buf中读取Header的Value,并将完整的Header添加到动态表中。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"hf.Value, buf, err = d.readString(buf, wantStr)\nif err != nil {\n return err\n}\nd.buf = buf\nif it.indexed() {\n d.dynTab.add(hf)\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"},{"type":"strong"}],"text":"(*"},{"type":"text","marks":[{"type":"strong"}],"text":"Decoder).readString"},{"type":"text","text":": 从编码的字节数据中读取真实的Header数据。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"func (d *Decoder) readString(p []byte, wantStr bool) (s string, remain []byte, err error) {\n\tif len(p) == 0 {\n\t\treturn \"\", p, errNeedMore\n\t}\n\tisHuff := p[0]&128 != 0\n\tstrLen, p, err := readVarInt(7, p)\n\t// 省略校验逻辑\n\tif !isHuff {\n\t\tif wantStr {\n\t\t\ts = string(p[:strLen])\n\t\t}\n\t\treturn s, p[strLen:], nil\n\t}\n\n\tif wantStr {\n\t\tbuf := bufPool.Get().(*bytes.Buffer)\n\t\tbuf.Reset() // don't trust others\n\t\tdefer bufPool.Put(buf)\n\t\tif err := huffmanDecode(buf, d.maxStrLen, p[:strLen]); err != nil {\n\t\t\tbuf.Reset()\n\t\t\treturn \"\", nil, err\n\t\t}\n\t\ts = buf.String()\n\t\tbuf.Reset() // be nice to GC\n\t}\n\treturn s, p[strLen:], nil\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" 首先判断字节数据是否是哈夫曼编码(和前面的"},{"type":"codeinline","content":[{"type":"text","text":"appendHpackString"}]},{"type":"text","text":"函数对应),然后通过"},{"type":"codeinline","content":[{"type":"text","text":"readVarInt"}]},{"type":"text","text":"读取数据的长度并赋值给"},{"type":"codeinline","content":[{"type":"text","text":"strLen"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果不是哈夫曼编码,则直接返回"},{"type":"codeinline","content":[{"type":"text","text":"strLen"}]},{"type":"text","text":"长度的数据。如果是哈夫曼编码,读取"},{"type":"codeinline","content":[{"type":"text","text":"strLen"}]},{"type":"text","text":"长度的数据,并用哈夫曼算法解码后再返回。"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"验证&总结"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在前面我们已经了解了HPACK索引列表,以及基于HPACK索引列表的编/解码流程。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面笔者最后验证一下已经编解码过后的Header,再次编解码时的大小。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"// 此处省略前面HAPACK编码和HPACK解码的demo\n// try again\nfmt.Println(\"try again: \")\nbuf.Reset()\nhenc.WriteField(hpack.HeaderField{Name: \"custom-header\", Value: \"custom-value\"}) // 编码已经编码过后的Header\nfmt.Println(hdec.Write(buf.Bytes())) // 解码\n// 输出:\n// ori size: 197, encoded size: 111\n// header field \":authority\" = \"dss0.bdstatic.com\"\n// header field \":method\" = \"GET\"\n// header field \":path\" = \"/5aV1bjqh_Q23odCf/static/superman/img/topnav/[email protected]\"\n// header field \":scheme\" = \"https\"\n// header field \"accept-encoding\" = \"gzip\"\n// header field \"user-agent\" = \"Go-http-client/2.0\"\n// header field \"custom-header\" = \"custom-value\"\n// 111 \n// try again:\n// header field \"custom-header\" = \"custom-value\"\n// 1 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"由上面最后一行的输出可知,解码仅用了一个字节,即本例中编码一个已经编码过的Header也仅需一个字节。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"综上:在一个连接上,client和server维护一个相同的HPACK索引列表,多个请求在发送和接收Header数据时可以分为两种情况。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"Header在HPACK索引列表里面,可以不用传输真实的Header数据仅需传输HPACK索引从而达到标头压缩的目的。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"Header不在HPACK索引列表里面,对大多数Header而言也仅需传输Header的Value以及Name的HPACK索引,从而减少Header数据的传输。同时,在发送和接收这样的Header数据时会更新各自的HPACK索引列表,以保证下一个请求传输的Header数据尽可能的少。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最后,由衷的感谢将HTTP2.0系列读完的读者,真诚的希望各位读者能够有所收获。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果大家有什么疑问可以在评论区和谐地讨论,笔者看到了也会及时回复,愿大家一起进步。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"注"},{"type":"text","text":":"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"1. 写本文时, 笔者所用go版本为: go1.14.2"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"2. 索引Header表示法和增加动态表Header表示法均为笔者自主命名,主要便于读者理解。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"参考:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"https://developers.google.com/web/fundamentals/performance/http2?hl=zh-cn"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章