specs

package
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2025 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ContentEncodingGzip    = "gzip"
	ContentEncodingDeflate = "deflate"
	ContentEncodingBrotli  = "br"
)

ContentEncoding represents the content encoding types used in HTTP responses.

These constants are used to specify the encoding of the response body, allowing clients to understand how to decode the content. The values are based on the IANA HTTP Content-Encoding registry.

Reference: https://www.iana.org/assignments/http-parameters/http-parameters.xhtml

View Source
const (
	ContentTypeUndefined = ""
	ContentTypeRaw       = "application/octet-stream"
	ContentTypePlain     = "text/plain"
	ContentTypeRichText  = "application/rtf"
	ContentTypeMarkdown  = "text/markdown"

	ContentTypeHTML       = "text/html"
	ContentTypeCSV        = "text/csv"
	ContentTypeCSS        = "text/css"
	ContentTypePDF        = "application/pdf"
	ContentTypeJavaScript = "text/javascript"
	ContentTypeFontTTF    = "font/ttf"

	ContentTypeAVI  = "video/x-msvideo"
	ContentTypeWAV  = "audio/wav"
	ContentTypeMP3  = "audio/mpeg"
	ContentTypeMP4  = "video/mp4"
	ContentTypeMPEG = "video/mpeg"
	ContentTypeMPV  = "video/MPV"
	ContentTypeMKV  = "application/x-matroska"

	ContentTypeAVIF = "image/avif"
	ContentTypeBMP  = "image/bmp"
	ContentTypeGIF  = "image/gif"
	ContentTypeJPEG = "image/jpeg"
	ContentTypePNG  = "image/png"
	ContentTypeWEBP = "image/webp"
	ContentTypeSVG  = "image/svg+xml"

	ContentTypeJson           = "application/json"
	ContentTypeXml            = "application/xml"
	ContentTypeMsgpack        = "application/msgpack"
	ContentTypeProtobuf       = "application/x-protobuf"
	ContentTypeForm           = "application/x-www-form-urlencoded"
	ContentTypeMultipart      = "multipart/form-data"
	ContentTypeMultipartMixed = "multipart/mixed"
)

ContentType defines the content type of a file or data.

It is used to specify the media type of the content being sent or received. This is useful in HTTP headers, file uploads, and other scenarios where the type of content needs to be communicated clearly. The constants defined here are commonly used content types. The values are based on the MIME types as defined in RFC 2045 and other relevant standards.

For more information, see: https://www.iana.org/assignments/media-types/media-types.xhtml

View Source
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"

TimeFormat is the format used for HTTP date headers.

Variables

View Source
var (
	ErrClosed                  = errors.New("closed")
	ErrTimeout                 = errors.New("timeout")
	ErrCancelled               = context.Canceled
	ErrProtocol                = NewOpError("protocol", "implementation error")
	ErrTooLarge                = NewOpError("read", "too large content")
	ErrTrailerEOF              = NewOpError("read", "unexpected EOF reading trailer")
	ErrUnknownTransferEncoding = NewOpError("http", "unknown transfer encoding")
	ErrUnknownContentEncoding  = NewOpError("http", "unknown content encoding")
)

Functions

func BasicAuthHeader

func BasicAuthHeader(username, password string) string

BasicAuthHeader creates a Basic Authentication header from a username and password.

func BearerAuthHeader

func BearerAuthHeader(token string) string

BearerAuthHeader creates a Bearer Authentication header from a token.

func MatchContentType added in v1.0.3

func MatchContentType(header *Header, expected string) bool

MatchContentType reports whether the Content-Type header value of h matches the expected media type exactly (ignoring parameters and case).

For example, if the header contains "application/json; charset=utf-8" and expected is "application/json", it returns true.

func NewOpError

func NewOpError(op OpName, format string, a ...any) error

NewOpError creates a new OpError with the specified operation and formatted error message.

func ParseBasicAuthHeader

func ParseBasicAuthHeader(header string) (username, password string, err error)

ParseBasicAuthHeader parses a Basic Authentication header and returns the username and password.

func ParseBearerAuthHeader

func ParseBearerAuthHeader(header string) (token string, err error)

ParseBearerAuthHeader parses a Bearer Authentication header and returns the token.

Types

type Cookie struct {
	Name  string
	Value string

	Domain  string
	MaxAge  uint64
	Expires time.Time
	Path    string

	HttpOnly bool
	Secure   bool
	SameSite CookieSameSite
}

Cookie represents an HTTP cookie with its attributes.

func (*Cookie) IsExpired

func (cookie *Cookie) IsExpired(now time.Time) bool

IsExpired checks if the cookie is expired based on the current time. If MaxAge is set, it will update the Expires time accordingly. If MaxAge is negative, it indicates the cookie is already expired. If Expires is set and the current time is after Expires, the cookie is expired

type CookieJar

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

CookieJar is a thread-safe cookie storage that allows storing and retrieving cookies based on the host they are associated with. It uses the Effective TLD Plus One (eTLD+1) rule to determine the host for which the cookies are valid.

func NewCookieJar

func NewCookieJar() *CookieJar

NewCookieJar creates a new CookieJar instance.

func (*CookieJar) Cookies

func (jar *CookieJar) Cookies(host string) iter.Seq[Cookie]

Cookies returns an iterator over all cookies associated with the given host.

func (*CookieJar) GetCookie

func (jar *CookieJar) GetCookie(host string, name string) *Cookie

GetCookie retrieves a cookie by its host and name.

If the cookie is expired, it will be removed from the jar. If the host is not valid or the cookie does not exist, it returns nil.

func (*CookieJar) SetCookie

func (jar *CookieJar) SetCookie(host string, cookie Cookie)

SetCookie sets a single cookie for the specified host.

func (*CookieJar) SetCookies

func (jar *CookieJar) SetCookies(host string, cookies []Cookie)

SetCookies sets multiple cookies for the specified host.

func (*CookieJar) SetCookiesIter

func (jar *CookieJar) SetCookiesIter(host string, cookies iter.Seq[Cookie])

SetCookiesIter sets multiple cookies for the specified host using an iterator.

type CookieSameSite

type CookieSameSite string

CookieSameSite defines the SameSite attribute for cookies.

const (
	CookieSameSiteLaxMode    CookieSameSite = "Lax"
	CookieSameSiteStrictMode CookieSameSite = "Strict"
	CookieSameSiteNoneMode   CookieSameSite = "None"
)

CookieSameSite modes define how cookies are sent with cross-site requests.

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

Header represents a collection of HTTP headers and cookies. It provides methods to set, get, and manipulate headers and cookies.

func NewHeader

func NewHeader(configure ...func(header *Header)) *Header

NewHeader creates a new Header instance with optional configuration functions.

func WithBearerAuthHeader

func WithBearerAuthHeader(header *Header, token string) *Header

WithBearerAuthHeader adds a Bearer Authentication header to the provided Header.

func WithChunkedEncoding

func WithChunkedEncoding(header *Header) *Header

WithChunkedEncoding sets the Transfer-Encoding header to "chunked".

func (*Header) All

func (header *Header) All() iter.Seq2[string, string]

All returns an iterator over all headers in the Header instance.

func (*Header) Any

func (header *Header) Any() bool

Any checks if the Header contains any headers.

func (*Header) AnyCookies

func (header *Header) AnyCookies() bool

AnyCookies checks if the Header contains any cookies.

func (*Header) Clone

func (header *Header) Clone() *Header

Clone creates a deep copy of the Header instance.

func (*Header) Cookies

func (header *Header) Cookies() iter.Seq[Cookie]

Cookies returns an iterator over all cookies in the Header instance.

func (*Header) Del

func (header *Header) Del(name string)

Del removes a header by its name.

func (*Header) DelCookie

func (header *Header) DelCookie(name string)

DelCookie removes a cookie by its name.

func (*Header) Get

func (header *Header) Get(name string) string

Get retrieves the value of a header by its name.

func (*Header) GetCookie

func (header *Header) GetCookie(name string) *Cookie

GetCookie retrieves a cookie by its name.

func (*Header) Has

func (header *Header) Has(name string) bool

Has checks if a header with the specified name exists.

func (*Header) HasCookie

func (header *Header) HasCookie(name string) bool

HasCookie checks if a cookie with the specified name exists.

func (*Header) Set

func (header *Header) Set(name, value string)

Set adds or updates a header with the specified name and value.

func (*Header) SetCookie

func (header *Header) SetCookie(cookie Cookie)

SetCookie adds or updates a cookie in the Header instance.

func (*Header) SetCookieValue

func (header *Header) SetCookieValue(name, value string)

SetCookieValue sets a cookie with the specified name and value.

func (*Header) TryGet

func (header *Header) TryGet(name string) (string, bool)

TryGet attempts to retrieve the value of a header by its name.

type HttpMethod

type HttpMethod string
const (
	HttpMethodGet     HttpMethod = "GET"
	HttpMethodPost    HttpMethod = "POST"
	HttpMethodPut     HttpMethod = "PUT"
	HttpMethodDelete  HttpMethod = "DELETE"
	HttpMethodOptions HttpMethod = "OPTIONS"
	HttpMethodHead    HttpMethod = "HEAD"
	HttpMethodConnect HttpMethod = "CONNECT"
	HttpMethodPatch   HttpMethod = "PATCH"
	HttpMethodTrace   HttpMethod = "TRACE"

	MethodPreface HttpMethod = "PRI"
)

HttpMethod constants represent the standard HTTP methods as defined in RFC 7231 and related specifications. These methods are used to indicate the desired action to be performed on a resource identified by a URL.

func (HttpMethod) IsPostable

func (method HttpMethod) IsPostable() bool

IsPostable checks if the HttpMethod is suitable for sending a request body.

func (HttpMethod) IsReplyable

func (method HttpMethod) IsReplyable() bool

IsReplyable checks if the HttpMethod can have a response.

func (HttpMethod) IsValid

func (method HttpMethod) IsValid() bool

IsValid checks if the HttpMethod is one of the standard HTTP methods.

type OpError

type OpError struct {
	Op  OpName
	Err error
}

OpError represents an error that occurred during a plow operation.

func (*OpError) Error

func (e *OpError) Error() string

Error implements the error interface for OpError.

func (*OpError) Match

func (e *OpError) Match(err error) bool

Match checks if the OpError matches another error based on operation and underlying error.

func (*OpError) String

func (e *OpError) String() string

String formats the OpError as a string, including the operation if it exists.

type OpName

type OpName string

OpName represents an operation in the plow.

type Query

type Query map[string]string

Query represents a parsed query string from a URL.

func ParseQuery

func ParseQuery(query string) Query

ParseQuery parses a query string into a Query map.

func (Query) Any

func (q Query) Any() bool

Any checks if the Query contains any key-value pairs.

func (Query) String

func (q Query) String() string

String returns the query string representation of the Query.

type StatusCode

type StatusCode uint16

StatusCode represents an HTTP status code.

const (
	StatusCodeUndefined StatusCode = 0

	StatusCodeContinue           StatusCode = 100
	StatusCodeSwitchingProtocols StatusCode = 101
	StatusCodeProcessing         StatusCode = 102
	StatusCodeEarlyHints         StatusCode = 103

	StatusCodeOK                   StatusCode = 200
	StatusCodeCreated              StatusCode = 201
	StatusCodeAccepted             StatusCode = 202
	StatusCodeNonAuthoritativeInfo StatusCode = 203
	StatusCodeNoContent            StatusCode = 204
	StatusCodeResetContent         StatusCode = 205
	StatusCodePartialContent       StatusCode = 206
	StatusCodeMultiStatus          StatusCode = 207
	StatusCodeAlreadyReported      StatusCode = 208
	StatusCodeIMUsed               StatusCode = 226

	StatusCodeMultipleChoices   StatusCode = 300
	StatusCodeMovedPermanently  StatusCode = 301
	StatusCodeFound             StatusCode = 302
	StatusCodeSeeOther          StatusCode = 303
	StatusCodeNotModified       StatusCode = 304
	StatusCodeUseProxy          StatusCode = 305
	StatusCodeTemporaryRedirect StatusCode = 307
	StatusCodePermanentRedirect StatusCode = 308

	StatusCodeBadRequest                   StatusCode = 400
	StatusCodeUnauthorized                 StatusCode = 401
	StatusCodePaymentRequired              StatusCode = 402
	StatusCodeForbidden                    StatusCode = 403
	StatusCodeNotFound                     StatusCode = 404
	StatusCodeMethodNotAllowed             StatusCode = 405
	StatusCodeNotAcceptable                StatusCode = 406
	StatusCodeProxyAuthRequired            StatusCode = 407
	StatusCodeRequestTimeout               StatusCode = 408
	StatusCodeConflict                     StatusCode = 409
	StatusCodeGone                         StatusCode = 410
	StatusCodeLengthRequired               StatusCode = 411
	StatusCodePreconditionFailed           StatusCode = 412
	StatusCodeRequestEntityTooLarge        StatusCode = 413
	StatusCodeRequestURITooLong            StatusCode = 414
	StatusCodeUnsupportedMediaType         StatusCode = 415
	StatusCodeRequestedRangeNotSatisfiable StatusCode = 416
	StatusCodeExpectationFailed            StatusCode = 417
	StatusCodeTeapot                       StatusCode = 418
	StatusCodeMisdirectedRequest           StatusCode = 421
	StatusCodeUnprocessableEntity          StatusCode = 422
	StatusCodeLocked                       StatusCode = 423
	StatusCodeFailedDependency             StatusCode = 424
	StatusCodeTooEarly                     StatusCode = 425
	StatusCodeUpgradeRequired              StatusCode = 426
	StatusCodePreconditionRequired         StatusCode = 428
	StatusCodeTooManyRequests              StatusCode = 429
	StatusCodeRequestHeaderFieldsTooLarge  StatusCode = 431
	StatusCodeUnavailableForLegalReasons   StatusCode = 451

	StatusCodeInternalServerError           StatusCode = 500
	StatusCodeNotImplemented                StatusCode = 501
	StatusCodeBadGateway                    StatusCode = 502
	StatusCodeServiceUnavailable            StatusCode = 503
	StatusCodeGatewayTimeout                StatusCode = 504
	StatusCodeHTTPVersionNotSupported       StatusCode = 505
	StatusCodeVariantAlsoNegotiates         StatusCode = 506
	StatusCodeInsufficientStorage           StatusCode = 507
	StatusCodeLoopDetected                  StatusCode = 508
	StatusCodeNotExtended                   StatusCode = 510
	StatusCodeNetworkAuthenticationRequired StatusCode = 511
)

Predefined HTTP status codes as per RFC 7231 and related specifications. These codes are used to indicate the result of an HTTP request.

func (StatusCode) Detail

func (code StatusCode) Detail() []byte

Detail returns the standard text description for the status code.

func (StatusCode) Formatted

func (code StatusCode) Formatted() []byte

Formatted returns the status code as a byte slice formatted for HTTP responses.

func (StatusCode) IsRedirect

func (code StatusCode) IsRedirect() bool

IsRedirect checks if the status code indicates a redirection.

func (StatusCode) IsReplyable

func (code StatusCode) IsReplyable() bool

IsReplyable returns true if the status code is suitable for a reply.

func (StatusCode) IsValid

func (code StatusCode) IsValid() bool

IsValid checks if the status code is within the valid range of HTTP status codes.

type Url

type Url struct {
	// Url raw component before escaping
	Scheme, Username, Password,
	Host, Path, Fragment string
	Port uint16

	// Query map of raw unescaped values represents of url Query.
	Query Query

	// PathSegments slice of raw unescaped components of Path.
	//
	// ParseUrl will ignore this field.
	// if PathSegments provided String will use this and escape every segment.
	PathSegments []string
}

Url represents URL with its components.

func MustParseUrl

func MustParseUrl(url string) *Url

MustParseUrl is a helper function that parses a URL string and panics if it fails.

func ParseUrl

func ParseUrl(url string) (*Url, error)

ParseUrl parses a URL string and returns a Url object.

func (*Url) EscapedPath added in v1.0.5

func (url *Url) EscapedPath() string

EscapedPath returns the escaped form of Path. In general there are multiple possible escaped forms of any path. EscapedPath returns PathSegments when it is provided. Otherwise, EscapedPath ignores PathSegments and computes an escaped form of Path.

func (*Url) String

func (url *Url) String() string

String returns the string representation of the URL. It constructs the URL from its components, escaping them as necessary.

Jump to

Keyboard shortcuts

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