mediatype

package
v0.0.0-...-c05fae0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2023 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package mediatype provides an implementation of RFC 6838 media types (also known as mime types). The package offers a type MediaType that can be used to conveniently work with media types. In addition, the mediatype package implements a media type negotiation algorithm that can be used to process a HTTP Accept header.

This package only understands media types in the format "type/subtype", optionally followed by parameters. This package does not support media types that only consist of a major type.

A MediaType value can identify a concrete type or a wildcard type. You can use MediaType.IsCompatibleWith and MediaType.Includes to find out if two media types fit together. There are different kinds of wildcard types supported by the mediatype package:

  • The special media type "*/*" includes any other media type
  • A wildcard subtype matches all types in a specific tree. For example "text/*" matches all types beginning with "text/", such as "text/plain".
  • A suffix wildcard matches all types in a specific tree that have a given suffix. For example "application/*+json" matches "application/problem+json" and "application/json", but not "application/problem+xml". Note that this is the only special case of a wildcard. Arbitrary wildcards (as in "application/j*n") are not supported.

Index

Constants

View Source
const ParameterQuality = "q"

ParameterQuality is the type parameter identifying the quality value of a media type.

View Source
const TypeWildcard = "*"

TypeWildcard defines the character that identifies wildcard types and subtypes.

Variables

View Source
var (
	Any = MediaType{"*", "*", nil, 1} // */*

	TextAny   = MediaType{"text", "*", nil, 1}     // text/*
	TextPlain = MediaType{"text", "plain", nil, 1} // text/plain

	ImageAny  = MediaType{"image", "*", nil, 1}    // image/*
	ImageJPEG = MediaType{"image", "jpeg", nil, 1} // image/jpeg
	ImagePNG  = MediaType{"image", "png", nil, 1}  // image/png
	ImageGIF  = MediaType{"image", "gif", nil, 1}  // image/gif

	AudioMPEG = MediaType{"audio", "mpeg", nil, 1}

	VideoMP4 = MediaType{"video", "mp4", nil, 1}

	ApplicationJSON        = MediaType{"application", "json", nil, 1}         // application/json
	ApplicationProblemJSON = MediaType{"application", "problem+json", nil, 1} // application/problem+json
	ApplicationXML         = MediaType{"application", "xml", nil, 1}          // application/xml
	ApplicationProblemXML  = MediaType{"application", "problem+xml", nil, 1}  // application/problem+xml
)

These constants define known media types. Using these constants is not required but can be more convenient than parsing strings every time.

Functions

func Equals

func Equals(t1 MediaType, t2 MediaType) bool

Equals compares t1 to t2 and returns true if both media types should be considered equal. This method checks parameter equality as well. If you only want to check for equal types, use EqualsType.

func EqualsType

func EqualsType(t1 MediaType, t2 MediaType) bool

EqualsType checks if t1 and t2 describe the same fundamental type. In contrast to Equals this method ignores any type parameters. Wildcards and their subtypes are NOT considered equal.

Types

type MediaType

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

The MediaType implements a RFC 6838 media type. A media type value is immutable. Instead of mutating a media type, use the "With..." methods to create a copy with the appropriate values.

var Nil MediaType

Nil is a special MediaType that indicates "no media type". The nil value for MediaType is Nil. This value is usually accompanied by an error giving the reason why a valid media type could not be constructed.

The Nil type has some special semantics:

  • The type, subtype and suffix are all empty
  • Nil is not contained in any other type, nor does it contain other types
  • Nil is incompatible with other types, even "*/*"
  • Nil is less specific than all non-Nil types
  • Nil has quality 0
  • MediaType.IsNil returns true

func MustParse

func MustParse(v string) MediaType

MustParse works like Parse but panics if v cannot be parsed.

func New

func New(tpe, subtype string, params ...string) MediaType

New creates a new media type with the given type, subtype and parameters. The type, subtype and parameter keys must be valid tokens as defined in RFC 1521 and RFC 2045. If this is not the case, Nil is returned.

The parameters are specified as a sequence of key, value pairs. If an uneven number of parameters is supplied, the last one will be ignored.

Types like "*/example" will be converted to "*/*".

func NewWithQuality

func NewWithQuality(tpe, subtype string, q float32, params ...string) MediaType

func Parse

func Parse(v string) (t MediaType, err error)

Parse parses v into a MediaType. If v does not describe a media type in a valid way, err will be non-nil. Depending on the type of error t might still be a valid media type. Especially if parsing media type parameters cause an error, t will still be set to the media type without parameters.

func (MediaType) Equals

func (t MediaType) Equals(other MediaType) bool

Equals compares t to other and returns true if both media types should be considered equal. This method checks parameter equality as well. If you only want to check for equal types, use MediaType.EqualsType.

func (MediaType) EqualsType

func (t MediaType) EqualsType(other MediaType) bool

EqualsType checks if t and other describe the same fundamental type. In contrast to MediaType.Equals this method ignores any type parameters. Wildcards and their subtypes are NOT considered equal.

func (MediaType) FullType

func (t MediaType) FullType() string

FullType returns the full type of t in the format type/subtype.

func (MediaType) HasHigherPriority

func (t MediaType) HasHigherPriority(other MediaType) bool

HasHigherPriority indicates whether t has a higher priority than other. The priority is mainly determined by the MediaType.Quality of a media type, where a higher quality indicates a higher priority. If t and other have the same quality, the more specific type has higher priority (as indicated by MediaType.IsMoreSpecific).

func (MediaType) HasLowerPriority

func (t MediaType) HasLowerPriority(other MediaType) bool

HasLowerPriority indicates whether t has a lower priority than other. This is the inverse to MediaType.HasHigherPriority.

func (MediaType) HasParameter

func (t MediaType) HasParameter(key string) bool

HasParameter checks if a parameter with the specified key is defined in t.

func (MediaType) Includes

func (t MediaType) Includes(other MediaType) bool

Includes checks whether t includes other. Inclusion rules are as follows:

  • The wildcard type "*/*" includes every other type.
  • A subtype wildcard like "example/*" includes every type in its subtree.
  • A suffix wildcard like "example/*+json" includes types in the same tree ending with the same suffix. For example both "example/json" and "example/foo+json" are included in "example/*+json".
  • A concrete type like "application/json" only includes itself.

Type parameters are not considered for inclusion.

Note that this method is not symmetric. "text/*" includes "text/plain" but not the other way round. If you need a symmetric variant, use MediaType.IsCompatibleWith instead.

func (MediaType) IsCompatibleWith

func (t MediaType) IsCompatibleWith(other MediaType) bool

IsCompatibleWith checks whether t and other are compatible with each other. This is a symmetric version of MediaType.Includes. See the documentation on MediaType.Includes for a definition of the inclusion rules.

func (MediaType) IsConcrete

func (t MediaType) IsConcrete() bool

IsConcrete indicates whether t is a concrete media type (that is not a wildcard). Nil is the only type that is neither concrete nor a wildcard.

func (MediaType) IsLessSpecific

func (t MediaType) IsLessSpecific(other MediaType) bool

IsLessSpecific indicates whether t is less specific than other. This is the inverse to MediaType.IsMoreSpecific.

func (MediaType) IsMoreSpecific

func (t MediaType) IsMoreSpecific(other MediaType) bool

IsMoreSpecific indicates whether t is more specific than other. The specificity of a type can fall in one of 4 classes (ordered from more specific to less specific):

  1. Concrete types like "application/json"
  2. Suffix wildcards like "application/*+json"
  3. Wildcard subtypes like "example/*"
  4. General wildcards like "*/*"
  5. The Nil type

If t and other fall into the same specificity class, the type with more parameters is more specific.

func (MediaType) IsNil

func (t MediaType) IsNil() bool

IsNil checks whether t identifies the Nil type (and should thus be considered invalid).

func (MediaType) IsWildcardSubtype

func (t MediaType) IsWildcardSubtype() bool

IsWildcardSubtype indicates whether t describes a wildcard subtype or a suffix wildcard. Both "example/*" and "example/*+json" are considered wildcard subtypes. Nil is the only type that is neither concrete nor a wildcard.

func (MediaType) IsWildcardType

func (t MediaType) IsWildcardType() bool

IsWildcardType indicates whether t describes the "*/*" type. Nil is the only type that is neither concrete nor a wildcard.

func (MediaType) MarshalText

func (t MediaType) MarshalText() ([]byte, error)

MarshalText serializes t as a string.

func (MediaType) Parameter

func (t MediaType) Parameter(key string) string

Parameter returns the value for the parameter key from t. If no such parameter exists, an empty string is returned.

func (MediaType) Parameters

func (t MediaType) Parameters() map[string]string

Parameters returns a non-nil map of all parameters of t.

func (MediaType) Quality

func (t MediaType) Quality() float32

Quality returns a parsed value for the "q" parameter of t. If t does not have a "q" parameter, 1 is returned. If the q-value cannot be parsed, 0 is returned. Nil has quality 0.

func (*MediaType) Scan

func (t *MediaType) Scan(value any) error

Scan implements sql.Scanner so MediaType values can be read from databases transparently. Currently, only database types that map to string are supported. Please consult database-specific driver documentation for matching types.

func (MediaType) String

func (t MediaType) String() string

String returns a string representation of the media type. The resulting string conforms to the syntax required by the Content-Type HTTP header.

func (MediaType) Subtype

func (t MediaType) Subtype() string

Subtype returns the minor type of t ("json" in "application/json").

func (MediaType) SubtypeSuffix

func (t MediaType) SubtypeSuffix() string

SubtypeSuffix returns the subtype suffix (if any). For example "application/problem+json" has a subtype suffix of "json". If t does not have a subtype suffix, an empty string is returned.

func (MediaType) Type

func (t MediaType) Type() string

Type returns the major type of t ("application" in "application/json").

func (*MediaType) UnmarshalText

func (t *MediaType) UnmarshalText(data []byte) (err error)

UnmarshalText deserializes string data.

func (MediaType) Value

func (t MediaType) Value() (driver.Value, error)

Value implements sql.Valuer so that MediaType values can be written to databases transparently. Currently, MediaType values map to strings. Please consult database-specific driver documentation for matching types.

func (MediaType) WithExactParameters

func (t MediaType) WithExactParameters(params map[string]string) MediaType

WithExactParameters returns a new media type with the specified set of parameters.

In contrast to MediaType.WithParameters any existing parameters of t are discarded.

func (MediaType) WithParameters

func (t MediaType) WithParameters(params map[string]string) MediaType

WithParameters returns a new media type with all parameters from t and the specified params. If a parameter is present in t and params, the value from params takes precedence.

In contrast to MediaType.WithExactParameters this method retains the parameters of t that are not set in params.

func (MediaType) WithQuality

func (t MediaType) WithQuality(q float32) MediaType

WithQuality returns a new media type that is equivalent to t but has the quality parameter "q" set to q. The value q is rounded to 3 decimal places (as per the spec). q is not normalized any further, values outside the [0, 1] interval are taken as-is. You can use [MediaType.WithNormalizedQuality] to make sure the quality value is within bounds.

func (MediaType) WithSubtype

func (t MediaType) WithSubtype(subtype string) MediaType

WithSubtype returns a new media type with its subtype set to subtype. If t.IsNil() is true or subtype is not a valid token, Nil is returned.

func (MediaType) WithType

func (t MediaType) WithType(tpe string) MediaType

WithType returns a new media type with its type set to tpe. If t.IsNil() is true or tpe is not a valid token, Nil is returned.

func (MediaType) WithoutParameters

func (t MediaType) WithoutParameters(params ...string) MediaType

WithoutParameters returns a new media type with some or all parameters of t removed. If you don't specify any params, the returned media type will not have any parameters set. If you do specify at least one param, only the specified parameters will be removed.

type MediaTypes

type MediaTypes []MediaType

MediaTypes is a list of MediaType objects. The MediaTypes type implements an algorithm for content type negotiation.

A MediaTypes can be used to represent an Accept header of an HTTP request.

MediaTypes implements sort.Interface. A sorted lists orders media types in descending order by MediaType.HasHigherPriority.

func ParseList

func ParseList(l ...string) MediaTypes

ParseList parses one or more comma separated lists of media types. This function can be used to parse an Accept header into a MediaTypes list.

In contrast to ParseListStrict this function discards invalid media types silently.

func ParseListStrict

func ParseListStrict(l ...string) (MediaTypes, error)

ParseListStrict parses one or more comma separated lists of media types. If an invalid media type is encountered, an empty list and an error is returned. This function can be used to parse an Accept header into a MediaTypes list.

In contrast to ParseList this function aborts with an error if an invalid media type is found.

func (MediaTypes) Best

func (l MediaTypes) Best() MediaType

Best returns the media type from l that has the highest priority. If l is empty, Nil is returned.

func (MediaTypes) BestMatch

func (l MediaTypes) BestMatch(available ...MediaType) MediaType

BestMatch compares l with the available media types and selects the best match. If no matches are available, Nil is returned.

func (MediaTypes) FindMatches

func (l MediaTypes) FindMatches(available ...MediaType) MediaTypes

FindMatches returns a list of matching content types between l and the list of available content types. A match is a content type that fits both a media type (or wildcard) in l and a media type (or wildcard) in the available types. The match will always be the more concrete of the two types. The quality of a match will be set to the product of the qualities of the matching types from l and the available types.

If l is an empty list, every available type is considered a match. If the available list is empty, there will be no matches. An empty return value indicates that no matches were found.

The returned list is not sorted. Sorting the list would give you all matching media types in decreasing order of priority. It is strongly recommended to use a stable sorting algorithm to preserve the order of types with equal priorities.

func (MediaTypes) GetType

func (l MediaTypes) GetType(t MediaType) MediaType

GetType returns the first element of l whose type equals t, or Nil if no such element exists.

func (MediaTypes) Includes

func (l MediaTypes) Includes(t MediaType) bool

Includes determines if any of the types in l include t.

func (MediaTypes) Len

func (l MediaTypes) Len() int

Len implements sort.Interface.

func (MediaTypes) Less

func (l MediaTypes) Less(i, j int) bool

Less implements sort.Interface.

func (MediaTypes) MarshalText

func (l MediaTypes) MarshalText() ([]byte, error)

MarshalText serializes l as a string.

func (*MediaTypes) Scan

func (l *MediaTypes) Scan(value any) error

Scan implements sql.Scanner so MediaTypes can be read from databases transparently. Currently, only database types that map to string are supported. Please consult database-specific driver documentation for matching types.

func (MediaTypes) String

func (l MediaTypes) String() string

String returns a string representation of l that can be used as the value for an Accept header.

func (MediaTypes) Swap

func (l MediaTypes) Swap(i, j int)

Swap implements sort.Interface.

func (*MediaTypes) UnmarshalText

func (l *MediaTypes) UnmarshalText(data []byte) (err error)

UnmarshalText deserializes string data.

func (MediaTypes) Value

func (l MediaTypes) Value() (driver.Value, error)

Value implements sql.Valuer so that MediaTypes can be written to databases transparently. Currently, MediaTypes map to strings. Please consult database-specific driver documentation for matching types.

Jump to

Keyboard shortcuts

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