Documentation
¶
Overview ¶
Package httphead reads and parses the heads of HTTP/1.x messages, the start line and the header fields, strictly where a lax reading lets two parties read one message in two ways, as in request smuggling, and leniently where that is safe (RFC 9110, RFC 9112). It also tells how a message's body is delimited and splits request targets. It reads nothing beyond the empty line that ends a head, so that the body and any next message stay in the reader, and it allocates one string per head, which the start line parts and the fields are substrings of.
It depends on the standard library alone and has no package initialisation beyond a table, so that sniffers and servers can use it at a small cost; net/http's parser would add crypto/tls and the HTTP/2 machinery to a program.
Example ¶
package main
import (
"bufio"
"fmt"
"io"
"strings"
"github.com/djylb/netx/httphead"
)
func main() {
br := bufio.NewReader(strings.NewReader("POST http://example.com/form HTTP/1.1\r\n" +
"Host: example.com\r\nContent-Length: 5\r\nConnection: keep-alive\r\n\r\nhello"))
head, err := httphead.Read(br, nil, 64<<10)
if err != nil {
fmt.Println(err)
return
}
req, err := httphead.ParseRequest(string(head), nil)
if err != nil {
fmt.Println(err)
return
}
target, _ := httphead.ParseTarget(req.Method, req.Target)
framing, n, _ := httphead.RequestBody(req.Header, req.Minor)
body := make([]byte, n)
_, _ = io.ReadFull(br, body) // the body stays in br
fmt.Println(req.Method, target.Host, target.Path, framing, n, string(body), req.Header.HasToken("Connection", "Keep-Alive"))
}
Output: POST example.com /form length 5 hello true
Index ¶
- Variables
- func ContentLength(h Header) (length int64, hasLength bool, err error)
- func ParseChunkSize(line []byte) (int64, error)
- func ParseVersion(v string) (int, error)
- func Read(r *bufio.Reader, buf []byte, limit int) ([]byte, error)
- func Tokens(list string) func(yield func(string) bool)
- func TrimOWS(s string) string
- func ValidFieldName(s string) bool
- func ValidFieldValue[T ~string | ~[]byte](s T) bool
- type Field
- type Form
- type Framing
- type Header
- func (h *Header) Add(name, value string)
- func (h *Header) AppendTo(b []byte) ([]byte, error)
- func (h *Header) Count(name string) int
- func (h *Header) Del(name string)
- func (h *Header) Get(name string) string
- func (h *Header) Has(name string) bool
- func (h *Header) HasToken(name, token string) bool
- func (h *Header) Set(name, value string)
- func (h *Header) Values(name string) []string
- type Request
- type Response
- type Target
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMalformed reports a head that violates the syntax. ErrMalformed = errors.New("httphead: malformed message") // ErrTooLarge reports a head, line or section over its limit. ErrTooLarge = errors.New("httphead: head too large") // ErrVersion reports an HTTP version other than 1.x, such as HTTP/2.0, // which a server answers with 505 HTTP Version Not Supported. ErrVersion = errors.New("httphead: unsupported HTTP version") // ErrTransferCoding reports a request transfer coding other than // chunked alone, which a server answers with 501 Not Implemented. ErrTransferCoding = errors.New("httphead: unsupported transfer coding") )
Errors of reading and parsing. Parse errors match ErrMalformed, or one of the more precise errors, and carry a description.
Functions ¶
func ContentLength ¶
ContentLength returns the validated length and whether the field is present.
func ParseChunkSize ¶
ParseChunkSize parses the chunk-size line of a chunked body, without its line ending: hexadecimal digits, then nothing or chunk extensions after a semicolon, which are checked for control characters and otherwise ignored (RFC 9112, section 7.1.1).
func ParseVersion ¶
ParseVersion parses "HTTP/1.x" and returns the minor version, 1 for any x from 1. Other versions of the right form, such as "HTTP/2.0", give ErrVersion, and anything else ErrMalformed; the version is case-sensitive.
func Read ¶
Read reads a message head, the start line and the header fields up to and including the empty line, from r into buf, reusing its storage, and returns it; at most limit bytes, counting empty lines before the start line, which it skips (RFC 9112, section 2.2). Lines may be longer than r's buffer. It returns io.EOF when r ends before any byte of a start line, io.ErrUnexpectedEOF when it ends inside a head, and ErrTooLarge for a head over limit bytes; what it read so far is returned with the error.
func Tokens ¶
Tokens returns the elements of the comma-separated list s, with whitespace trimmed and empty elements skipped (RFC 9110, section 5.6.1).
func ValidFieldName ¶
ValidFieldName reports whether s is a token, as a field name or a method must be (RFC 9110, section 5.6.2).
func ValidFieldValue ¶
ValidFieldValue reports whether s may be a field value: visible ASCII, spaces, tabs and bytes from 0x80, without other control characters (RFC 9110, section 5.5).
Types ¶
type Field ¶
type Field struct {
Name, Value string
}
Field is a header field.
func ParseField ¶
ParseField parses a single field line without its line ending.
type Form ¶
type Form uint8
Form is the form of a request-target (RFC 9112, section 3.2).
const ( // OriginForm is a path with an optional query, such as "/a?b". OriginForm Form = iota // AbsoluteForm is an absolute URI, such as "http://example.com/a", // which requests to proxies carry. AbsoluteForm // AuthorityForm is the host and port of a CONNECT request. AuthorityForm // AsteriskForm is the "*" of a server-wide OPTIONS request. AsteriskForm )
type Framing ¶
type Framing uint8
Framing is how the body of a message is delimited (RFC 9112, section 6).
func RequestBody ¶
RequestBody returns how the body of a request with header h and minor version minor is delimited, and the length for Length. It refuses what a recipient could read in two ways: Transfer-Encoding with Content-Length, Transfer-Encoding in HTTP/1.0 (RFC 9112, section 6.1), and invalid or differing Content-Length values, of which equal ones in a list or in several fields are taken as one (section 6.3). A transfer coding other than chunked alone gives ErrTransferCoding. A Content-Length of 0 is NoBody.
func ResponseBody ¶
ResponseBody returns how the body of a response with status code and header h, to a request with method method, is delimited, the length for Length, and, for Chunked and UntilClose, the transfer codings other than chunked as sent, such as "gzip", which the body is still encoded with. A response to HEAD or successful CONNECT and one with a 1xx, 204 or 304 code has no body, whatever its fields say. Transfer-Encoding overrides Content-Length (RFC 9112, section 6.3); a list that does not end in chunked is read until close, and one that holds chunked before its end is an error, as are invalid or differing Content-Length values. A response with neither is read until close.
type Header ¶
type Header []Field
Header holds the fields of a head in the order they were sent, with their names as sent. Names are matched case-insensitively. The zero Header is empty and ready for use. Its methods all take a pointer, as Add, Set and Del change its length in place, and so are called on a Header held in a variable or a field.
func ParseHeader ¶
ParseHeader parses header field lines, such as a trailer section, appending them to fields. Lines end in CRLF or in LF alone (RFC 9112, section 2.2); an empty line ends the section and must be the last. It refuses what would let two readers disagree on the fields: a CR other than before LF, a line that starts with whitespace (obsolete line folding), whitespace before the colon, a name that is not a token, and control characters in a value. Values have their surrounding whitespace trimmed.
func (*Header) AppendTo ¶
AppendTo appends the fields to b as header lines, "Name: value" and CRLF each. It returns ErrMalformed, and b as it was, when a name is not a token or a value holds a byte a field value cannot, such as CR or LF, so that no field can add a line.
func (*Header) HasToken ¶
HasToken reports whether the comma-separated lists in the fields named name hold token, case-insensitively, as for "Connection: keep-alive, Upgrade".
type Request ¶
type Request struct {
// Method is the method as sent; methods are case-sensitive.
Method string
// Target is the request-target as sent; see ParseTarget.
Target string
// Proto is the version as sent, such as "HTTP/1.1".
Proto string
Header Header
// Minor is the minor version: 0 for HTTP/1.0, 1 for HTTP/1.1 and later
// minor versions, which are compatible with it (RFC 9110, section 2.5).
Minor int
}
Request is a parsed request head.
func ParseRequest ¶
ParseRequest parses a request head as Read returns it, converted to a string. The fields are appended to fields, which may be nil, reusing its storage. See ParseHeader for what is accepted. The request line is method, target and version separated by single spaces; the target cannot hold spaces or control characters.
type Response ¶
type Response struct {
Proto string
// Reason is the reason phrase as sent, which may be empty.
Reason string
Header Header
Minor int
// Code is the status code, from 100 to 999.
Code int
}
Response is a parsed response head.
func ParseResponse ¶
ParseResponse parses a response head as Read returns it, converted to a string, appending the fields to fields as ParseRequest does. The status line is the version, a three-digit code and an optional reason phrase, which may hold spaces.
type Target ¶
type Target struct {
// Scheme is the scheme of an absolute URI, in lower case.
Scheme string
// Authority is the host and port of an absolute URI or of the authority
// form, as sent, which a forwarded request's Host field carries.
Authority string
// Host is the host of Authority: a name as sent, an IPv4 address, or an
// IPv6 address without brackets, with a zone decoded from "%25" (RFC
// 6874).
Host string
// Path is the origin-form of the target, which a request sent to the
// origin carries: the target itself for the origin and asterisk forms,
// and for an absolute URI its path and query without the fragment, "/"
// for an empty path, or "*" for an empty path of an OPTIONS request
// (section 3.2.4). It is empty for the authority form.
Path string
// Port is the port of Authority, or 0 when it has none or an empty one;
// port 0 itself is refused.
Port uint16
// Form is the form the target was sent in.
Form Form
}
Target is a parsed request-target.
func ParseTarget ¶
ParseTarget parses the request-target of a request with method method: the authority form for CONNECT, compared case-insensitively, and the other forms for other methods. An absolute URI must have a host and no user information, which is deprecated and would let the host differ from the one a reader expects (RFC 9110, section 4.2.4). A host is an IP literal, IPv6 in brackets, or a name of letters, digits, hyphens, underscores and dots, of at most 255 bytes. With an error it returns the zero Target.