http2

package module
v0.0.0-...-dfd1b46 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2016 License: MIT Imports: 15 Imported by: 0

README

A Go implementation of the HTTP/2 protocol.

It is useful for client/server application development using the HTTP/2 connection/stream directly.

currently under heavy development.

Features

  • Server/Client Connection
  • Negotiation (ALPN, Upgrade)
  • Flow Control
  • Multiplexing without head-of-line blocking
  • Graceful Shutdown

Requirements

  • Golang 1.5+

Installation

go get github.com/nekolunar/http2

Documentation

Benchmarks

  • 2.2 GHz Intel Core i7
  • 16 GB 1600 MHz DDR3
  • Concurrency: C(1|8|64|512)
  • Request/Response Data Length: 1024 Bytes
HTTP/2 over TLS (ALPN)
go test -bench BenchmarkConnReadWriteTLS -benchmem

BenchmarkConnReadWriteTLS_1K_C1-8      50000         33666 ns/op        4083 B/op         32 allocs/op
BenchmarkConnReadWriteTLS_1K_C8-8      50000         34544 ns/op        4080 B/op         32 allocs/op
BenchmarkConnReadWriteTLS_1K_C64-8     50000         34277 ns/op        4058 B/op         32 allocs/op
BenchmarkConnReadWriteTLS_1K_C512-8    50000         33966 ns/op        3880 B/op         30 allocs/op
HTTP/2 over TCP (Upgrade)
go test -bench BenchmarkConnReadWriteTCP -benchmem

BenchmarkConnReadWriteTCP_1K_C1-8      50000         30090 ns/op        4065 B/op         32 allocs/op
BenchmarkConnReadWriteTCP_1K_C8-8      50000         30610 ns/op        4062 B/op         32 allocs/op
BenchmarkConnReadWriteTCP_1K_C64-8     50000         30673 ns/op        4040 B/op         32 allocs/op
BenchmarkConnReadWriteTCP_1K_C512-8   100000         30715 ns/op        3965 B/op         31 allocs/op

License

MIT license. See LICENSE for details.

Documentation

Index

Constants

View Source
const (
	ProtocolTLS = "h2"
	ProtocolTCP = "h2c"
)

HTTP/2 Version Identification, defined in RFC 7540 section 3.1.

View Source
const ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"

ClientPreface represents client-side HTTP/2 connection preface, defined in RFC 7540 section 3.5.

Variables

View Source
var ErrClosed = errors.New("http2: connection has been closed")

ErrClosed represents connection already closed error.

Functions

func CanonicalHTTP2HeaderKey

func CanonicalHTTP2HeaderKey(s string) string

CanonicalHTTP2HeaderKey returns the canonical format of the header key s.

Types

type Config

type Config struct {
	// InitialSettings specifies the Http2Settings to use for the initial
	// connection settings exchange. If nil, empty settings is used.
	InitialSettings Settings

	// HandshakeTimeout specifies the duration for the handshake to complete.
	HandshakeTimeout time.Duration

	// AllowLowTLSVersion controls whether a server allows the client's
	// TLSVersion is lower than TLS 1.2.
	AllowLowTLSVersion bool

	// ReadBufSize and WriteBufSize specify I/O buffer sizes. If the buffer
	// size is zero, then a default value of 4096 is used. The I/O buffer sizes
	// do not limit the size of the frames that can be sent or received.
	ReadBufSize, WriteBufSize int
}

A Config structure is used to configure a HTTP/2 client or server connection.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

A Conn represents a HTTP/2 connection.

func ClientConn

func ClientConn(rawConn net.Conn, config *Config, req *http.Request) *Conn

ClientConn returns a new HTTP/2 client side connection using rawConn as the underlying transport. If config is nil, the default configuration is used. The req parameter optionally specifies the request to send for client's upgrade.

func ServerConn

func ServerConn(rawConn net.Conn, config *Config) *Conn

ServerConn returns a new HTTP/2 server side connection using rawConn as the underlying transport. If config is nil, the default configuration is used.

func (*Conn) Close

func (c *Conn) Close() error

Close closed this connection by sending GOAWAY frame.

func (*Conn) CloseTimeout

func (c *Conn) CloseTimeout(timeout time.Duration) error

CloseTimeout closes this connection by sending GOAWAY frame and waits for shutdown to finish.

The timeout parameter specifies a time duration this connection will wait for all streams to be closed before closing the connection.

If timeout is zero, it will close Immediately.

func (*Conn) Closed

func (c *Conn) Closed() bool

Closed returns whether or not this connection was closed.

func (*Conn) Flush

func (c *Conn) Flush() error

Flush sends buffered frame to the remote connection.

func (*Conn) GoAwayReceived

func (c *Conn) GoAwayReceived() (bool, *GoAwayFrame)

GoAwayReceived returns whether or not a GOAWAY was received from the remote connection.

func (*Conn) GoAwaySent

func (c *Conn) GoAwaySent() (bool, *GoAwayFrame)

GoAwaySent returns whether or not a GOAWAY was sent to the remote connection.

func (*Conn) Handshake

func (c *Conn) Handshake() error

Handshake runs the client or server handshake protocol if it has not yet been run. Most uses of this package need not call Handshake explicitly: the first Read or Write will call it automatically.

func (*Conn) InitialRecvWindow

func (c *Conn) InitialRecvWindow(streamID uint32) uint32

InitialRecvWindow returns the initial receive flow control window size for the given stream.

func (*Conn) InitialSendWindow

func (c *Conn) InitialSendWindow(uint32) uint32

InitialSendWindow returns the initial send flow control window size for the given stream.

func (*Conn) LastStreamID

func (c *Conn) LastStreamID() uint32

LastStreamID returns the ID of the remote-stream last successfully created.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Conn) NextStreamID

func (c *Conn) NextStreamID() (uint32, error)

NextStreamID returns the next generated stream id.

func (*Conn) NumActiveStreams

func (c *Conn) NumActiveStreams() uint32

NumActiveStreams returns the number of active streams(OPEN or HALF CLOSED).

func (*Conn) ReadFrame

func (c *Conn) ReadFrame() (Frame, error)

ReadFrame reads a frame from the connection.

func (*Conn) RecvWindow

func (c *Conn) RecvWindow(streamID uint32) uint32

RecvWindow returns the portion of the recieve flow control window for the given stream that is currently available for receiving frames which are subject to flow control.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Conn) RemoteSettings

func (c *Conn) RemoteSettings() Settings

RemoteSettings returns the remote-side http2settings.

func (*Conn) SendWindow

func (c *Conn) SendWindow(streamID uint32) uint32

SendWindow returns the portion of the send flow control window for the given stream that is currently available for sending frames which are subject to flow control.

func (*Conn) ServerConn

func (c *Conn) ServerConn() bool

ServerConn returns whether or not this connection is the server-side.

func (*Conn) Settings

func (c *Conn) Settings() Settings

Settings returns the local-side http2settings.

func (*Conn) WriteFrame

func (c *Conn) WriteFrame(frame Frame) error

WriteFrame writes a frame to the connection.

type ConnError

type ConnError struct {
	Err error
	ErrCode
}

ConnError represents connection error, defined in RFC 7540 section 5.4.1.

func (ConnError) Error

func (e ConnError) Error() string

type DataFrame

type DataFrame struct {
	StreamID  uint32
	Data      io.Reader
	DataLen   int
	PadLen    uint8
	EndStream bool
}

DataFrame represents the DATA frame, defined in RFC 7540 section 6.1.

func (*DataFrame) EndOfStream

func (f *DataFrame) EndOfStream() bool

func (*DataFrame) Stream

func (f *DataFrame) Stream() uint32

func (*DataFrame) Type

func (f *DataFrame) Type() FrameType

type Dialer

type Dialer struct {
	// DialTCP specifies the dial function for creating unencrypted
	// TCP connections.
	// If DialTCP is nil, net.Dial is used.
	DialTCP func(network, addr string) (net.Conn, error)

	// DialTLS specifies an optional dial function for creating
	// TLS connections for non-proxied HTTPS requests.
	//
	// If DialTLS is nil, DialTCP and TLSClientConfig are used.
	//
	// If DialTLS is set, the TLSClientConfig are ignored.
	DialTLS func(network, addr string) (net.Conn, error)

	// Config specifies the connection configuration to use with
	// ClientConn. If nil, the default configuration is used.
	Config *Config

	// TLSClientConfig specifies the TLS configuration to use with
	// tls.Client. If nil, the default configuration is used.
	TLSClientConfig *tls.Config
}

A Dialer contains options for connecting to HTTP/2 server.

func (*Dialer) Dial

func (d *Dialer) Dial(protocol, address string, request *http.Request) (*Conn, error)

Dial connects to the address on the named protocol and then initiates a HTTP/2 negotiation, returning the resulting HTTP/2 connection.

Allowed protocols are "h2" (ALPN) and "h2c" (Upgrade).

The request parameter specifies an HTTP/1.1 request to send for client's upgrade.

If request is nil, default upgrade request are used.

If protocol is "h2", request are ignored.

Examples:

d.Dial("h2", "google.com:https", nil)
d.Dial("h2c", "12.34.56.78:http", nil)
d.Dial(http2.ProtocolTCP, request.Host, request)

type ErrCode

type ErrCode uint32

ErrCode represents error codes, defined in RFC 7540 section 7.

const (
	ErrCodeNo                 ErrCode = 0x0
	ErrCodeProtocol           ErrCode = 0x1
	ErrCodeInternal           ErrCode = 0x2
	ErrCodeFlowControl        ErrCode = 0x3
	ErrCodeSettingsTimeout    ErrCode = 0x4
	ErrCodeStreamClosed       ErrCode = 0x5
	ErrCodeFrameSize          ErrCode = 0x6
	ErrCodeRefusedStream      ErrCode = 0x7
	ErrCodeCancel             ErrCode = 0x8
	ErrCodeCompression        ErrCode = 0x9
	ErrCodeConnect            ErrCode = 0xa
	ErrCodeEnhanceYourCalm    ErrCode = 0xb
	ErrCodeInadequateSecurity ErrCode = 0xc
	ErrCodeHTTP11Required     ErrCode = 0xd
)

func (ErrCode) String

func (e ErrCode) String() string

type Flags

type Flags uint8

Flags is An 8-bit field reserved for boolean flags specific to the frame type.

const (
	FlagEndStream  Flags = 0x1
	FlagEndHeaders Flags = 0x4
	FlagAck        Flags = 0x1
	FlagPadded     Flags = 0x8
	FlagPriority   Flags = 0x20
)

func (Flags) Has

func (f Flags) Has(v Flags) bool

type Frame

type Frame interface {
	Type() FrameType
	Stream() uint32
	EndOfStream() bool
}

Frame is the base interface implemented by all frame types.

type FrameType

type FrameType uint8

FrameType represents Frame Type Registry, defined in RFC 7540 section 11.2.

const (
	FrameData         FrameType = 0x0
	FrameHeaders      FrameType = 0x1
	FramePriority     FrameType = 0x2
	FrameRSTStream    FrameType = 0x3
	FrameSettings     FrameType = 0x4
	FramePushPromise  FrameType = 0x5
	FramePing         FrameType = 0x6
	FrameGoAway       FrameType = 0x7
	FrameWindowUpdate FrameType = 0x8
	FrameContinuation FrameType = 0x9
)

func (FrameType) String

func (t FrameType) String() string

type GoAwayFrame

type GoAwayFrame struct {
	LastStreamID uint32
	ErrCode
	DebugData []byte
}

GoAwayFrame represents the GOAWAY frame, defined in RFC 7540 section 6.8.

func (*GoAwayFrame) EndOfStream

func (f *GoAwayFrame) EndOfStream() bool

func (*GoAwayFrame) Stream

func (f *GoAwayFrame) Stream() uint32

func (*GoAwayFrame) Type

func (f *GoAwayFrame) Type() FrameType

type Handler

type Handler func(*Conn)

A Handler for reading or writing frames from the connection.

type HandshakeError

type HandshakeError string

HandshakeError represents connection handshake error.

func (HandshakeError) Error

func (e HandshakeError) Error() string
type Header map[string][]string

Header is A collection of headers sent or received via HTTP/2.

func (Header) Add

func (h Header) Add(key, value string)

Add adds the header value for the given header key.

func (Header) Authority

func (h Header) Authority() string

Authority returns the authority header.

func (Header) Del

func (h Header) Del(key string)

Del removes the header value for the given header key.

func (Header) Get

func (h Header) Get(key string) string

Get return the header value for the given header key.

func (Header) Len

func (h Header) Len() (n int)

Len returns the number of header values in header.

func (Header) Method

func (h Header) Method() string

Method returns the method header.

func (Header) Path

func (h Header) Path() string

Path returns the path header.

func (Header) Scheme

func (h Header) Scheme() string

Scheme returns the scheme header.

func (Header) Set

func (h Header) Set(key, value string)

Set sets the header value for the given header key.

func (Header) SetAuthority

func (h Header) SetAuthority(value string)

SetAuthority sets the authority header.

func (Header) SetMethod

func (h Header) SetMethod(value string)

SetMethod sets the method header.

func (Header) SetPath

func (h Header) SetPath(value string)

SetPath sets the path header.

func (Header) SetScheme

func (h Header) SetScheme(value string)

SetScheme sets the scheme header.

func (Header) SetStatus

func (h Header) SetStatus(value string)

SetStatus sets the status header.

func (Header) Status

func (h Header) Status() string

Status returns the status header.

type HeadersFrame

type HeadersFrame struct {
	StreamID uint32
	Header
	Priority
	PadLen    uint8
	EndStream bool
}

HeadersFrame represents the HEADERS frame, defined in RFC 7540 section 6.2.

func (*HeadersFrame) EndOfStream

func (f *HeadersFrame) EndOfStream() bool

func (*HeadersFrame) HasPriority

func (f *HeadersFrame) HasPriority() bool

func (*HeadersFrame) Stream

func (f *HeadersFrame) Stream() uint32

func (*HeadersFrame) Type

func (f *HeadersFrame) Type() FrameType

type MalformedError

type MalformedError string

MalformedError represents Malformed Requests and Responses, defined in RFC 7540 section 8.1.2.6.

func (MalformedError) Error

func (e MalformedError) Error() string

type PingFrame

type PingFrame struct {
	Ack  bool
	Data [8]byte
}

PingFrame represents the PING frame, defined in RFC 7540 section 6.7.

func (*PingFrame) EndOfStream

func (f *PingFrame) EndOfStream() bool

func (*PingFrame) Stream

func (f *PingFrame) Stream() uint32

func (*PingFrame) Type

func (f *PingFrame) Type() FrameType

type Priority

type Priority struct {
	StreamDependency uint32
	Weight           uint8
	Exclusive        bool
}

Priority is the Stream prioritzation parameters.

type PriorityFrame

type PriorityFrame struct {
	StreamID uint32
	Priority
}

PriorityFrame represents the PRIORITY frame, defined in RFC 7540 section 6.3.

func (*PriorityFrame) EndOfStream

func (f *PriorityFrame) EndOfStream() bool

func (*PriorityFrame) Stream

func (f *PriorityFrame) Stream() uint32

func (*PriorityFrame) Type

func (f *PriorityFrame) Type() FrameType

type PushPromiseFrame

type PushPromiseFrame struct {
	StreamID         uint32
	PromisedStreamID uint32
	Header
	PadLen uint8
}

PushPromiseFrame represents the PUSH_PROMISE frame, defined in RFC 7540 section 6.6.

func (*PushPromiseFrame) EndOfStream

func (f *PushPromiseFrame) EndOfStream() bool

func (*PushPromiseFrame) Stream

func (f *PushPromiseFrame) Stream() uint32

func (*PushPromiseFrame) Type

func (f *PushPromiseFrame) Type() FrameType

type RSTStreamFrame

type RSTStreamFrame struct {
	StreamID uint32
	ErrCode
}

RSTStreamFrame represents the RST_STREAM frame, defined in RFC 7540 section 6.4.

func (*RSTStreamFrame) EndOfStream

func (f *RSTStreamFrame) EndOfStream() bool

func (*RSTStreamFrame) Stream

func (f *RSTStreamFrame) Stream() uint32

func (*RSTStreamFrame) Type

func (f *RSTStreamFrame) Type() FrameType

type Server

type Server struct {
	Addr      string      // TCP address to listen on, ":http" if empty
	Handler   Handler     // handler to invoke, cannot be nil
	Config    *Config     // optional connection config, used by ServerConn
	TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS
}

A Server defines parameters for running an HTTP/2 server.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe listens on the TCP network address s.Addr and then calls Serve to handle requests on incoming connections. Accepted connections are configured to enable TCP no-delay. If s.Addr is blank, ":http" is used. ListenAndServe always returns a non-nil error.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS listens on the TCP network address s.Addr and then calls Serve to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP no-delay.

Filenames containing a certificate and matching private key for the server must be provided if the Server's TLSConfig.Certificates is not populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

If s.Addr is blank, ":https" is used.

ListenAndServeTLS always returns a non-nil error.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new service goroutine for each. Serve always returns a non-nil error.

type SettingID

type SettingID uint16

SettingID represents SETTINGS Parameters, defined in RFC 7540 section 6.5.2.

const (
	SettingHeaderTableSize      SettingID = 0x1
	SettingEnablePush           SettingID = 0x2
	SettingMaxConcurrentStreams SettingID = 0x3
	SettingInitialWindowSize    SettingID = 0x4
	SettingMaxFrameSize         SettingID = 0x5
	SettingMaxHeaderListSize    SettingID = 0x6
)

func (SettingID) String

func (id SettingID) String() string

type Settings

type Settings []setting

Settings for local or remote in an HTTP/2 connection.

func (Settings) HeaderTableSize

func (s Settings) HeaderTableSize() uint32

HeaderTableSize returns the SettingHeaderTableSize value.

func (Settings) InitialWindowSize

func (s Settings) InitialWindowSize() uint32

InitialWindowSize returns the SettingInitialWindowSize value.

func (Settings) MaxConcurrentStreams

func (s Settings) MaxConcurrentStreams() uint32

MaxConcurrentStreams returns the SettingMaxConcurrentStreams value.

func (Settings) MaxFrameSize

func (s Settings) MaxFrameSize() uint32

MaxFrameSize returns the SettingMaxFrameSize value.

func (Settings) MaxHeaderListSize

func (s Settings) MaxHeaderListSize() uint32

MaxHeaderListSize returns the SettingMaxHeaderListSize value.

func (Settings) PushEnabled

func (s Settings) PushEnabled() bool

PushEnabled returns the SettingEnablePush value.

func (*Settings) SetHeaderTableSize

func (s *Settings) SetHeaderTableSize(value uint32) error

SetHeaderTableSize sets the SettingHeaderTableSize value.

func (*Settings) SetInitialWindowSize

func (s *Settings) SetInitialWindowSize(value uint32) error

SetInitialWindowSize sets the SettingInitialWindowSize value.

func (*Settings) SetMaxConcurrentStreams

func (s *Settings) SetMaxConcurrentStreams(value uint32) error

SetMaxConcurrentStreams sets the SettingMaxConcurrentStreams value.

func (*Settings) SetMaxFrameSize

func (s *Settings) SetMaxFrameSize(value uint32) error

SetMaxFrameSize sets the SettingMaxFrameSize value.

func (*Settings) SetMaxHeaderListSize

func (s *Settings) SetMaxHeaderListSize(value uint32) error

SetMaxHeaderListSize sets the SettingMaxHeaderListSize value.

func (*Settings) SetPushEnabled

func (s *Settings) SetPushEnabled(enabled bool) error

SetPushEnabled sets the SettingEnablePush value.

func (*Settings) SetValue

func (s *Settings) SetValue(id SettingID, value uint32) error

SetValue sets the setting value for the given setting ID.

func (Settings) String

func (s Settings) String() string

func (Settings) Value

func (s Settings) Value(id SettingID) uint32

Value returns the setting value for the given setting ID. If not present, returns default value.

type SettingsFrame

type SettingsFrame struct {
	Ack bool
	Settings
}

SettingsFrame represents the SETTINGS frame, defined in RFC 7540 section 6.5.

func (*SettingsFrame) EndOfStream

func (f *SettingsFrame) EndOfStream() bool

func (*SettingsFrame) Stream

func (f *SettingsFrame) Stream() uint32

func (*SettingsFrame) Type

func (f *SettingsFrame) Type() FrameType

type StreamError

type StreamError struct {
	Err error
	ErrCode
	StreamID uint32
}

StreamError represents stream error, defined in RFC 7540 section 5.4.2.

func (StreamError) Error

func (e StreamError) Error() string

type StreamErrorList

type StreamErrorList []*StreamError

StreamErrorList is a list of *StreamErrors.

func (StreamErrorList) Err

func (e StreamErrorList) Err() error

Err returns the error.

func (StreamErrorList) Error

func (e StreamErrorList) Error() string

type StreamState

type StreamState int32
const (
	StateIdle StreamState = iota
	StateReservedLocal
	StateReservedRemote
	StateOpen
	StateHalfClosedLocal
	StateHalfClosedRemote
	StateClosed
)

func (StreamState) String

func (state StreamState) String() string

type UnknownFrame

type UnknownFrame struct {
	FrameType
	StreamID uint32
	Flags
	Payload    io.Reader
	PayloadLen int
}

UnknownFrame represents not defined by the HTTP/2 spec.

func (*UnknownFrame) EndOfStream

func (f *UnknownFrame) EndOfStream() bool

func (*UnknownFrame) Stream

func (f *UnknownFrame) Stream() uint32

func (*UnknownFrame) Type

func (f *UnknownFrame) Type() FrameType

type WindowUpdateFrame

type WindowUpdateFrame struct {
	StreamID            uint32
	WindowSizeIncrement uint32
}

WindowUpdateFrame represents the WINDOW_UPDATE frame, defined in RFC 7540 section 6.9.

func (*WindowUpdateFrame) EndOfStream

func (f *WindowUpdateFrame) EndOfStream() bool

func (*WindowUpdateFrame) Stream

func (f *WindowUpdateFrame) Stream() uint32

func (*WindowUpdateFrame) Type

func (f *WindowUpdateFrame) Type() FrameType

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL