本文整理汇总了Golang中github.com/bradfitz/http2/hpack.NewEncoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewEncoder函数的具体用法?Golang NewEncoder怎么用?Golang NewEncoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewEncoder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServerPushTestGroup
func ServerPushTestGroup(ctx *Context) *TestGroup {
tg := NewTestGroup("8.2", "Server Push")
tg.AddTestCase(NewTestCase(
"Sends a PUSH_PROMISE frame",
"The endpoint MUST treat the receipt of a PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR.",
func(ctx *Context) (expected []Result, actual Result) {
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := commonHeaderFields(ctx)
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
var pp http2.PushPromiseParam
pp.StreamID = 1
pp.PromiseID = 3
pp.EndHeaders = true
pp.BlockFragment = buf.Bytes()
http2Conn.fr.WritePushPromise(pp)
actualCodes := []http2.ErrCode{http2.ErrCodeProtocol}
return TestConnectionError(ctx, http2Conn, actualCodes)
},
))
return tg
}
示例2: main
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() != 1 {
usage()
}
log.SetFlags(0)
host := flag.Arg(0)
app := &h2i{
host: host,
peerSetting: make(map[http2.SettingID]uint32),
}
app.henc = hpack.NewEncoder(&app.hbuf)
if err := app.Main(); err != nil {
if app.term != nil {
app.logf("%v\n", err)
} else {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "\n")
}
示例3: NewConnection
func NewConnection(host string, isTLS, sendPreface, sendSettingsInit bool) *Connection {
conn := &Connection{
Host: host,
IsTLS: isTLS,
IsPreface: sendPreface,
IsSendSettings: sendSettingsInit,
PeerSetting: make(map[http2.SettingID]uint32),
}
conn.HEnc = hpack.NewEncoder(&conn.HBuf)
raw, err := Dial(host, isTLS)
if err != nil {
conn.handleError(err)
return conn
}
fmt.Println(raw)
conn.Raw = raw
conn.SetupFramer()
if sendPreface {
conn.SendPreface()
}
if sendSettingsInit {
conn.SendInitSettings()
}
go func() { conn.readFrames() }()
return conn
}
示例4: TestHTTPHeaderFields
func TestHTTPHeaderFields(ctx *Context) {
PrintHeader("8.1.2. HTTP Header Fields", 1)
func(ctx *Context) {
desc := "Sends a HEADERS frame that contains the header field name in uppercase letters"
msg := "the endpoint MUST respond with a stream error of type PROTOCOL_ERROR."
result := false
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := []hpack.HeaderField{
pair(":method", "GET"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
pair("X-TEST", "test"),
}
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = true
hp.EndHeaders = true
hp.BlockFragment = buf.Bytes()
http2Conn.fr.WriteHeaders(hp)
timeCh := time.After(3 * time.Second)
loop:
for {
select {
case f := <-http2Conn.dataCh:
rf, ok := f.(*http2.RSTStreamFrame)
if ok {
if rf.ErrCode == http2.ErrCodeProtocol {
result = true
break loop
}
}
case <-http2Conn.errCh:
break loop
case <-timeCh:
break loop
}
}
PrintResult(result, desc, msg, 1)
}(ctx)
TestPseudoHeaderFields(ctx)
TestConnectionSpecificHeaderFields(ctx)
TestRequestPseudoHeaderFields(ctx)
TestMalformedRequestsAndResponses(ctx)
}
示例5: TestPriority
func TestPriority(ctx *Context) {
PrintHeader("6.3. PRIORITY", 0)
func(ctx *Context) {
desc := "Sends a PRIORITY frame with 0x0 stream identifier"
msg := "The endpoint MUST respond with a connection error of type PROTOCOL_ERROR."
result := false
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := []hpack.HeaderField{
pair(":method", "GET"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
}
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = false
hp.EndHeaders = true
hp.BlockFragment = buf.Bytes()
http2Conn.fr.WriteHeaders(hp)
fmt.Fprintf(http2Conn.conn, "\x00\x00\x05\x02\x00\x00\x00\x00\x00")
http2Conn.conn.Write(buf.Bytes())
fmt.Fprintf(http2Conn.conn, "\x80\x00\x00\x01\x0a")
timeCh := time.After(3 * time.Second)
loop:
for {
select {
case f := <-http2Conn.dataCh:
gf, ok := f.(*http2.GoAwayFrame)
if ok {
if gf.ErrCode == http2.ErrCodeProtocol {
result = true
}
}
case <-http2Conn.errCh:
break loop
case <-timeCh:
break loop
}
}
PrintResult(result, desc, msg, 0)
}(ctx)
PrintFooter()
}
示例6: TestMalformedRequestsAndResponses
func TestMalformedRequestsAndResponses(ctx *Context) {
PrintHeader("8.1.2.6. Malformed Requests and Responses", 2)
// 8.1.2.6. ボディを構成する DATA フレームペイロードの長さの合計が "content-length" ヘッダーフィールドの値と等しくない場合、リクエストやレスポンスは不正な形式になります。
func(ctx *Context) {
desc := "Sends a HEADERS frame that contains invalid \"content-length\" header field"
msg := "the endpoint MUST respond with a stream error of type PROTOCOL_ERROR."
result := false
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := []hpack.HeaderField{
pair(":method", "POST"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
pair("content-length", "1"),
}
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = false
hp.EndHeaders = true
hp.BlockFragment = buf.Bytes()
http2Conn.fr.WriteHeaders(hp)
http2Conn.fr.WriteData(1, true, []byte("test"))
timeCh := time.After(3 * time.Second)
loop:
for {
select {
case f := <-http2Conn.dataCh:
rf, ok := f.(*http2.RSTStreamFrame)
if ok {
if rf.ErrCode == http2.ErrCodeProtocol {
result = true
break loop
}
}
case <-http2Conn.errCh:
break loop
case <-timeCh:
break loop
}
}
PrintResult(result, desc, msg, 2)
}(ctx)
}
示例7: encodeHeaderNoImplicit
// like encodeHeader, but don't add implicit psuedo headers.
func encodeHeaderNoImplicit(t *testing.T, headers ...string) []byte {
var buf bytes.Buffer
enc := hpack.NewEncoder(&buf)
for len(headers) > 0 {
k, v := headers[0], headers[1]
headers = headers[2:]
if err := enc.WriteField(hpack.HeaderField{Name: k, Value: v}); err != nil {
t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err)
}
}
return buf.Bytes()
}
示例8: NewConnectionRaw
func NewConnectionRaw(c net.Conn, tls bool) *Connection {
conn := &Connection{
Host: "localhost",
IsTLS: tls,
Raw: c,
}
conn.HEnc = hpack.NewEncoder(&conn.HBuf)
conn.SetupFramer()
conn.SendInitSettings()
go func() { conn.readFrames() }()
return conn
}
示例9: newHTTP2Server
// newHTTP2Server constructs a ServerTransport based on HTTP2. ConnectionError is
// returned if something goes wrong.
func newHTTP2Server(conn net.Conn, maxStreams uint32) (_ ServerTransport, err error) {
framer := newFramer(conn)
// Send initial settings as connection preface to client.
// TODO(zhaoq): Have a better way to signal "no limit" because 0 is
// permitted in the HTTP2 spec.
var settings []http2.Setting
// TODO(zhaoq): Have a better way to signal "no limit" because 0 is
// permitted in the HTTP2 spec.
if maxStreams == 0 {
maxStreams = math.MaxUint32
} else {
settings = append(settings, http2.Setting{http2.SettingMaxConcurrentStreams, maxStreams})
}
if initialWindowSize != defaultWindowSize {
settings = append(settings, http2.Setting{http2.SettingInitialWindowSize, uint32(initialWindowSize)})
}
if err := framer.writeSettings(true, settings...); err != nil {
return nil, ConnectionErrorf("transport: %v", err)
}
// Adjust the connection flow control window if needed.
if delta := uint32(initialConnWindowSize - defaultWindowSize); delta > 0 {
if err := framer.writeWindowUpdate(true, 0, delta); err != nil {
return nil, ConnectionErrorf("transport: %v", err)
}
}
var buf bytes.Buffer
t := &http2Server{
conn: conn,
framer: framer,
hBuf: &buf,
hEnc: hpack.NewEncoder(&buf),
maxStreams: maxStreams,
controlBuf: newRecvBuffer(),
fc: &inFlow{limit: initialConnWindowSize},
sendQuotaPool: newQuotaPool(defaultWindowSize),
state: reachable,
writableChan: make(chan int, 1),
shutdownChan: make(chan struct{}),
activeStreams: make(map[uint32]*Stream),
streamSendQuota: defaultWindowSize,
}
go t.controller()
t.writableChan <- 0
return t, nil
}
示例10: NewServerConnection
func NewServerConnection(c net.Conn, tls bool) *Connection {
conn := &Connection{
Host: "localhost",
IsTLS: tls,
Raw: c,
PeerSetting: make(map[http2.SettingID]uint32),
IsSendSettings: true,
}
conn.HEnc = hpack.NewEncoder(&conn.HBuf)
conn.SetupFramer()
conn.readPreface()
conn.Framer.WriteSettings()
conn.Framer.WriteSettingsAck()
conn.Framer.WriteSettings()
conn.Framer.WriteSettingsAck()
go func() { conn.readFrames() }()
return conn
}
示例11: newHTTP2Client
// newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2
// and starts to receive messages on it. Non-nil error returns if construction
// fails.
func newHTTP2Client(addr string, authOpts []credentials.Credentials) (_ ClientTransport, err error) {
var (
connErr error
conn net.Conn
)
scheme := "http"
// TODO(zhaoq): Use DialTimeout instead.
for _, c := range authOpts {
if ccreds, ok := c.(credentials.TransportAuthenticator); ok {
scheme = "https"
// TODO(zhaoq): Now the first TransportAuthenticator is used if there are
// multiple ones provided. Revisit this if it is not appropriate. Probably
// place the ClientTransport construction into a separate function to make
// things clear.
conn, connErr = ccreds.Dial(addr)
break
}
}
if scheme == "http" {
conn, connErr = net.Dial("tcp", addr)
}
if connErr != nil {
return nil, ConnectionErrorf("transport: %v", connErr)
}
defer func() {
if err != nil {
conn.Close()
}
}()
// Send connection preface to server.
n, err := conn.Write(clientPreface)
if err != nil {
return nil, ConnectionErrorf("transport: %v", err)
}
if n != len(clientPreface) {
return nil, ConnectionErrorf("transport: preface mismatch, wrote %d bytes; want %d", n, len(clientPreface))
}
framer := http2.NewFramer(conn, conn)
if err := framer.WriteSettings(); err != nil {
return nil, ConnectionErrorf("transport: %v", err)
}
var buf bytes.Buffer
t := &http2Client{
target: addr,
conn: conn,
// The client initiated stream id is odd starting from 1.
nextID: 1,
writableChan: make(chan int, 1),
shutdownChan: make(chan struct{}),
errorChan: make(chan struct{}),
framer: framer,
hBuf: &buf,
hEnc: hpack.NewEncoder(&buf),
controlBuf: newRecvBuffer(),
sendQuotaPool: newQuotaPool(initialWindowSize),
scheme: scheme,
state: reachable,
activeStreams: make(map[uint32]*Stream),
maxStreams: math.MaxUint32,
authCreds: authOpts,
}
go t.controller()
t.writableChan <- 0
// Start the reader goroutine for incoming message. The threading model
// on receiving is that each transport has a dedicated goroutine which
// reads HTTP2 frame from network. Then it dispatches the frame to the
// corresponding stream entity.
go t.reader()
return t, nil
}
示例12: TestWindowUpdate
func TestWindowUpdate(ctx *Context) {
PrintHeader("6.9. WINDOW_UPDATE", 0)
func(ctx *Context) {
desc := "Sends a WINDOW_UPDATE frame with an flow control window increment of 0"
msg := "the endpoint MUST respond with a connection error of type PROTOCOL_ERROR."
result := false
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
http2Conn.fr.WriteWindowUpdate(0, 0)
timeCh := time.After(3 * time.Second)
loop:
for {
select {
case f := <-http2Conn.dataCh:
gf, ok := f.(*http2.GoAwayFrame)
if ok {
if gf.ErrCode == http2.ErrCodeProtocol {
result = true
break loop
}
}
case <-http2Conn.errCh:
break loop
case <-timeCh:
break loop
}
}
PrintResult(result, desc, msg, 0)
}(ctx)
func(ctx *Context) {
desc := "Sends a WINDOW_UPDATE frame with an flow control window increment of 0 on a stream"
msg := "the endpoint MUST respond with a connection error of type PROTOCOL_ERROR."
result := false
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := []hpack.HeaderField{
pair(":method", "GET"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
}
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = false
hp.EndHeaders = true
hp.BlockFragment = buf.Bytes()
http2Conn.fr.WriteHeaders(hp)
http2Conn.fr.WriteWindowUpdate(1, 0)
timeCh := time.After(3 * time.Second)
loop:
for {
select {
case f := <-http2Conn.dataCh:
gf, ok := f.(*http2.GoAwayFrame)
if ok {
if gf.ErrCode == http2.ErrCodeProtocol {
result = true
break loop
}
}
case <-http2Conn.errCh:
break loop
case <-timeCh:
break loop
}
}
PrintResult(result, desc, msg, 0)
}(ctx)
TestInitialFlowControlWindowSize(ctx)
PrintFooter()
}
示例13: CreateHttp2Conn
func CreateHttp2Conn(ctx *Context, sn bool) *Http2Conn {
var conn net.Conn
var err error
if ctx.Tls {
conn, err = connectTls(ctx)
} else {
conn, err = net.Dial("tcp", ctx.Authority())
}
if err != nil {
fmt.Printf("Unable to connect to the target server: %v\n", err)
os.Exit(1)
}
fmt.Fprintf(conn, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
fr := http2.NewFramer(conn, conn)
settings := map[http2.SettingID]uint32{}
if sn {
doneCh := make(chan bool, 1)
errCh := make(chan error, 1)
fr.WriteSettings()
go func() {
local := false
remote := false
for {
f, err := fr.ReadFrame()
if err != nil {
errCh <- err
return
}
switch f := f.(type) {
case *http2.SettingsFrame:
if f.IsAck() {
local = true
} else {
f.ForeachSetting(func(setting http2.Setting) error {
settings[setting.ID] = setting.Val
return nil
})
fr.WriteSettingsAck()
remote = true
}
}
if local && remote {
doneCh <- true
return
}
}
}()
select {
case <-doneCh:
// Nothing to. do
case <-errCh:
fmt.Println("HTTP/2 settings negotiation failed")
os.Exit(1)
case <-time.After(ctx.Timeout):
fmt.Println("HTTP/2 settings negotiation timeout")
os.Exit(1)
}
}
fr.AllowIllegalWrites = true
dataCh := make(chan http2.Frame)
errCh := make(chan error, 1)
http2Conn := &Http2Conn{
conn: conn,
fr: fr,
dataCh: dataCh,
errCh: errCh,
Settings: settings,
}
http2Conn.HpackEncoder = hpack.NewEncoder(&http2Conn.HeaderWriteBuf)
return http2Conn
}
示例14: TestPseudoHeaderFields
func TestPseudoHeaderFields(ctx *Context) {
PrintHeader("8.1.2.1. Pseudo-Header Fields", 2)
func(ctx *Context) {
desc := "Sends a HEADERS frame that contains the pseudo-header field defined for response"
msg := "the endpoint MUST respond with a stream error of type PROTOCOL_ERROR."
result := false
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := []hpack.HeaderField{
pair(":method", "GET"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
pair(":status", "200"),
}
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = true
hp.EndHeaders = true
hp.BlockFragment = buf.Bytes()
http2Conn.fr.WriteHeaders(hp)
timeCh := time.After(3 * time.Second)
loop:
for {
select {
case f := <-http2Conn.dataCh:
rf, ok := f.(*http2.RSTStreamFrame)
if ok {
if rf.ErrCode == http2.ErrCodeProtocol {
result = true
break loop
}
}
case <-http2Conn.errCh:
break loop
case <-timeCh:
break loop
}
}
PrintResult(result, desc, msg, 2)
}(ctx)
func(ctx *Context) {
desc := "Sends a HEADERS frame that contains the invalid pseudo-header field"
msg := "the endpoint MUST respond with a stream error of type PROTOCOL_ERROR."
result := false
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := []hpack.HeaderField{
pair(":method", "GET"),
pair(":scheme", "http"),
pair(":path", "/"),
pair(":authority", ctx.Authority()),
pair(":test", "test"),
}
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = true
hp.EndHeaders = true
hp.BlockFragment = buf.Bytes()
http2Conn.fr.WriteHeaders(hp)
timeCh := time.After(3 * time.Second)
loop:
for {
select {
case f := <-http2Conn.dataCh:
rf, ok := f.(*http2.RSTStreamFrame)
if ok {
if rf.ErrCode == http2.ErrCodeProtocol {
result = true
break loop
}
}
case <-http2Conn.errCh:
break loop
case <-timeCh:
break loop
}
//.........这里部分代码省略.........
示例15: HeadersTestGroup
func HeadersTestGroup(ctx *Context) *TestGroup {
tg := NewTestGroup("6.2", "HEADERS")
tg.AddTestCase(NewTestCase(
"Sends a HEADERS frame followed by any frame other than CONTINUATION",
"The endpoint MUST treat the receipt of any other type of frame as a connection error of type PROTOCOL_ERROR.",
func(ctx *Context) (expected []Result, actual Result) {
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
hdrs := commonHeaderFields(ctx)
var hp http2.HeadersFrameParam
hp.StreamID = 1
hp.EndStream = false
hp.EndHeaders = false
hp.BlockFragment = http2Conn.EncodeHeader(hdrs)
http2Conn.fr.WriteHeaders(hp)
http2Conn.fr.WriteData(1, true, []byte("test"))
actualCodes := []http2.ErrCode{http2.ErrCodeProtocol}
return TestConnectionError(ctx, http2Conn, actualCodes)
},
))
tg.AddTestCase(NewTestCase(
"Sends a HEADERS frame followed by a frame on a different stream",
"The endpoint MUST treat the receipt of a frame on a different stream as a connection error of type PROTOCOL_ERROR.",
func(ctx *Context) (expected []Result, actual Result) {
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
hdrs := commonHeaderFields(ctx)
var hp1 http2.HeadersFrameParam
hp1.StreamID = 1
hp1.EndStream = false
hp1.EndHeaders = false
hp1.BlockFragment = http2Conn.EncodeHeader(hdrs)
http2Conn.fr.WriteHeaders(hp1)
var hp2 http2.HeadersFrameParam
hp2.StreamID = 3
hp2.EndStream = true
hp2.EndHeaders = true
hp2.BlockFragment = http2Conn.EncodeHeader(hdrs)
http2Conn.fr.WriteHeaders(hp2)
actualCodes := []http2.ErrCode{http2.ErrCodeProtocol}
return TestConnectionError(ctx, http2Conn, actualCodes)
},
))
tg.AddTestCase(NewTestCase(
"Sends a HEADERS frame with 0x0 stream identifier",
"The endpoint MUST respond with a connection error of type PROTOCOL_ERROR.",
func(ctx *Context) (expected []Result, actual Result) {
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
hdrs := commonHeaderFields(ctx)
var hp http2.HeadersFrameParam
hp.StreamID = 0
hp.EndStream = true
hp.EndHeaders = true
hp.BlockFragment = http2Conn.EncodeHeader(hdrs)
http2Conn.fr.WriteHeaders(hp)
actualCodes := []http2.ErrCode{http2.ErrCodeProtocol}
return TestConnectionError(ctx, http2Conn, actualCodes)
},
))
tg.AddTestCase(NewTestCase(
"Sends a HEADERS frame with invalid pad length",
"The endpoint MUST treat this as a connection error of type PROTOCOL_ERROR.",
func(ctx *Context) (expected []Result, actual Result) {
http2Conn := CreateHttp2Conn(ctx, true)
defer http2Conn.conn.Close()
var buf bytes.Buffer
hdrs := commonHeaderFields(ctx)
enc := hpack.NewEncoder(&buf)
for _, hf := range hdrs {
_ = enc.WriteField(hf)
}
fmt.Fprintf(http2Conn.conn, "\x00\x00\x0f\x01\x0c\x00\x00\x00\x01")
http2Conn.conn.Write(buf.Bytes())
fmt.Fprintf(http2Conn.conn, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
actualCodes := []http2.ErrCode{http2.ErrCodeProtocol}
return TestConnectionError(ctx, http2Conn, actualCodes)
},
))
return tg
}