Skip to content

Instantly share code, notes, and snippets.

@zhuizhuhaomeng
Created May 14, 2020 15:58
Show Gist options
  • Save zhuizhuhaomeng/b8feb30d15d4cc73be4c8c94448cf31d to your computer and use it in GitHub Desktop.
Save zhuizhuhaomeng/b8feb30d15d4cc73be4c8c94448cf31d to your computer and use it in GitHub Desktop.

Revisions

  1. zhuizhuhaomeng created this gist May 14, 2020.
    42 changes: 42 additions & 0 deletions decode_header.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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)
    }