Skip to content

Instantly share code, notes, and snippets.

@tianchaijz
Forked from zhuizhuhaomeng/decode_header.go
Created September 16, 2020 09:35
Show Gist options
  • Save tianchaijz/55e3ecdcbabdc71d1c197ab6e69e4419 to your computer and use it in GitHub Desktop.
Save tianchaijz/55e3ecdcbabdc71d1c197ab6e69e4419 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"golang.org/x/net/http2/hpack"
)
func main() {
fmt.Println("nginx", "→", Encode("MYWS"))
fmt.Println("nginx", "→", Encode("nginx"))
fmt.Println("apache", "→", Encode("apache"))
fmt.Println("openresty+", "→", Encode("openresty+"))
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"))
fmt.Println("\\x87\\x3d\\x65\\xaa\\xc2\\xa1\\x3e\\xbf\\xdf", "→", Decode("\x87\x3d\x65\xaa\xc2\xa1\x3e\xbf\xdf"))
}
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment