我已经尝试研究 nginx 源代码有一段时间了。最近,Nginx 1.9.12 发布了,他们实现了“HTTP/2 中响应头的霍夫曼编码”。
在此版本中,我无法理解这一行,
static const u_char nginx[5] = "\x84\xaa\x63\x55\xe7";
或者,您可以在此处浏览源代码:https://trac.nginx.org/nginx/browser/nginx/src/http/v2/ngx_http_v2_filter_module.c#L146
这一行是 Nginx 用于插入 header “Server: nginx”的内容。
如果我想将其更改为“Apache”怎么办?我尝试将字符串“apache”转换为十六进制,然后用\xhh 表示法替换文件中生成的十六进制,并将 nginx[5] 更改为 nginx[6],因为字符串 apache 的长度为 6 个字符。
但是输出似乎不可预测。在在这里问这个问题之前我已经搜索了很多。
有人可以帮我看看这段代码是如何工作的以及如何替换文本吗?有任何脚本或在线网络应用程序可以使它更容易吗?
最佳答案
我编写了简单的 Go 脚本来转换 HPACK 压缩字符串:
package main
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"fmt"
"golang.org/x/net/http2/hpack"
)
// ////////////////////////////////////////////////////////////////////////////////// //
func main() {
fmt.Println("nginx", "→", Encode("nginx"))
fmt.Println("apache", "→", Encode("apache"))
fmt.Println("-----")
fmt.Println("\\x84\\xaa\\x63\\x55\\xe7", "→", Decode("\x84\xaa\x63\x55\xe7"))
fmt.Println("\\x84\\x1d\\x63\\x24\\xe5", "→", Decode("\x84\x1d\x63\x24\xe5"))
}
func Encode(s string) string {
var result string
hd := hpack.AppendHuffmanString(nil, s)
hl := hpack.HuffmanEncodeLength(s) | 0x80
result += RenderByte(byte(hl))
for _, b := range hd {
result += RenderByte(b)
}
return result
}
func Decode(s string) string {
data := []byte(s)
result, _ := hpack.HuffmanDecodeToString(data[1:])
return result
}
func RenderByte(b byte) string {
return fmt.Sprintf("\\x%x", b)
}
// ////////////////////////////////////////////////////////////////////////////////// //
关于nginx - 此代码如何产生字符串 "nginx"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35655448/