contenttype

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2023 License: Unlicense Imports: 4 Imported by: 19

README

Content-Type support library for Go

This library can be used to parse the value Content-Type header (if one is present) and select an acceptable media type from the Accept header of HTTP request.

Usage

Media types are stored in MediaType structure which has Type (e.g. application), Subtype (e.g. json) and Parameters (e.g. charset: utf-8) attributes. Media types are not stored in a string because media type parameters are part of the media type (RFC 7231, 3.1.1.1. Media Type). To convert a string to MediaType use NewMediaType. To convert MediaType back to string use String function. If the Content-Type header is not present in the request, an empty MediaType is returned.

To get the MediaType corresponding to the incoming request's Content-Type header call GetMediaType and pass the http.Request pointer to it, or to parse any media type string call ParseMediaType. Either function will return error if the value is malformed according to RFC 7231, 3.1.1.5. Content-Type.

To get an acceptable media type from an Accept header of the incoming request call GetAcceptableMediaType and pass the http.Request pointer to it and an array of all the acceptable media types. The function will return the best match following the negotiation rules written in RFC 7231, 5.3.2. Accept or an error if the header is malformed or the content type in the Accept header is not supported. If the Accept header is not present in the request, the first media type from the acceptable type list is returned. If you have an Accept header value string from a source other than req.Header.Values("Accept") you can parse that in the same way using GetAcceptableMediaTypeFromHeader.

import (
	"log"
	"github.com/elnormous/contenttype"
)

func handleRequest(responseWriter http.ResponseWriter, request *http.Request) {
    mediaType, mediaTypeError := contenttype.GetMediaType(request)
    if mediaTypeError != nil {
        // handle the error
    }
    log.Println("Media type:", mediaType.String())

    availableMediaTypes := []MediaType{
        contenttype.NewMediaType("application/json"),
        contenttype.NewMediaType("application/xml"),
    }

    accepted, extParameters, acceptError := contenttype.GetAcceptableMediaType(request, availableMediaTypes)
    if acceptError != nil {
        // handle the error
    }
    log.Println("Accepted media type:", accepted.String(), "extension parameters:", extParameters)
}

Documentation

Overview

Package contenttype implements HTTP Content-Type and Accept header parsers.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidMediaType is returned when the media type in the Content-Type or Accept header is syntactically invalid.
	ErrInvalidMediaType = errors.New("invalid media type")
	// ErrInvalidMediaRange is returned when the range of media types in the Content-Type or Accept header is syntactically invalid.
	ErrInvalidMediaRange = errors.New("invalid media range")
	// ErrInvalidParameter is returned when the media type parameter in the Content-Type or Accept header is syntactically invalid.
	ErrInvalidParameter = errors.New("invalid parameter")
	// ErrInvalidExtensionParameter is returned when the media type extension parameter in the Content-Type or Accept header is syntactically invalid.
	ErrInvalidExtensionParameter = errors.New("invalid extension parameter")
	// ErrNoAcceptableTypeFound is returned when Accept header contains only media types that are not in the acceptable media type list.
	ErrNoAcceptableTypeFound = errors.New("no acceptable type found")
	// ErrNoAvailableTypeGiven is returned when the acceptable media type list is empty.
	ErrNoAvailableTypeGiven = errors.New("no available type given")
	// ErrInvalidWeight is returned when the media type weight in Accept header is syntactically invalid.
	ErrInvalidWeight = errors.New("invalid weight")
)

Functions

func GetAcceptableMediaType

func GetAcceptableMediaType(request *http.Request, availableMediaTypes []MediaType) (MediaType, Parameters, error)

GetAcceptableMediaType chooses a media type from available media types according to the Accept. Returns the most suitable media type or an error if no type can be selected.

func GetAcceptableMediaTypeFromHeader added in v1.0.1

func GetAcceptableMediaTypeFromHeader(headerValue string, availableMediaTypes []MediaType) (MediaType, Parameters, error)

GetAcceptableMediaTypeFromHeader chooses a media type from available media types according to the specified Accept header value. Returns the most suitable media type or an error if no type can be selected.

Types

type MediaType

type MediaType struct {
	Type       string
	Subtype    string
	Parameters Parameters
}

MediaType holds the type, subtype and parameters of a media type.

func GetMediaType

func GetMediaType(request *http.Request) (MediaType, error)

GetMediaType gets the content of Content-Type header, parses it, and returns the parsed MediaType. If the request does not contain the Content-Type header, an empty MediaType is returned.

func NewMediaType

func NewMediaType(s string) MediaType

NewMediaType parses the string and returns an instance of MediaType struct.

func ParseMediaType added in v1.0.1

func ParseMediaType(s string) (MediaType, error)

ParseMediaType parses the given string as a MIME media type (with optional parameters) and returns it as a MediaType. If the string cannot be parsed an appropriate error is returned.

func (MediaType) Equal added in v1.0.4

func (mediaType MediaType) Equal(mt MediaType) bool

Equal checks whether the provided MIME media type matches this one including all parameters

Example

ExampleMediaType_MIME comparing two media types with their parameters

package main

import (
	"fmt"

	"github.com/elnormous/contenttype"
)

func main() {
	base := contenttype.NewMediaType("application/json; charset=utf-8")
	noMatch := contenttype.NewMediaType("application/json")
	match := contenttype.MediaType{Type: "application", Subtype: "json", Parameters: contenttype.Parameters{"charset": "utf-8"}}

	fmt.Printf("matches exactly: %v\n", base.Equal(base))
	fmt.Printf("matches exactly: %v\n", base.Equal(noMatch))
	fmt.Printf("matches exactly: %v\n", base.Equal(match))
}
Output:

matches exactly: true
matches exactly: false
matches exactly: true

func (MediaType) EqualsMIME added in v1.0.4

func (mediaType MediaType) EqualsMIME(mt MediaType) bool

EqualsMIME checks whether the base MIME types match

Example

ExampleMediaType_EqualsMIME comparing only on the MIME media type which must match both the type and subtype

package main

import (
	"fmt"

	"github.com/elnormous/contenttype"
)

func main() {
	base := contenttype.NewMediaType("application/json; q=0.01; charset=utf-8")
	noMatch := contenttype.NewMediaType("text/json")
	partialWildcard := contenttype.NewMediaType("application/*")
	diffParams := contenttype.MediaType{Type: "application", Subtype: "json", Parameters: contenttype.Parameters{"charset": "utf-8"}}
	match := contenttype.MediaType{Type: "application", Subtype: "json"}

	fmt.Printf("matches exactly: %v\n", base.EqualsMIME(base))
	fmt.Printf("matches exactly: %v\n", base.EqualsMIME(noMatch))
	fmt.Printf("matches exactly: %v\n", base.EqualsMIME(partialWildcard))
	fmt.Printf("matches exactly: %v\n", base.EqualsMIME(diffParams))
	fmt.Printf("matches exactly: %v\n", base.EqualsMIME(match))
}
Output:

matches exactly: true
matches exactly: false
matches exactly: false
matches exactly: true
matches exactly: true

func (MediaType) IsWildcard added in v1.0.4

func (mediaType MediaType) IsWildcard() bool

IsWildcard returns true if either the Type or Subtype are the wildcard character '*'

func (MediaType) MIME added in v1.0.3

func (mediaType MediaType) MIME() string

MIME returns the MIME type without any of the parameters

Example

ExampleMediaType_MIME comparing to MIME types

package main

import (
	"fmt"

	"github.com/elnormous/contenttype"
)

func main() {
	mt := contenttype.NewMediaType("application/json; charset=utf-8")
	fmt.Printf("MIME(): %s\n", mt.MIME())
	fmt.Printf("matches: application/json: %v\n", mt.MIME() == "application/json")
	fmt.Printf("matches: application/*: %v\n", mt.MIME() == "application/*")
	fmt.Printf("matches: text/plain: %v\n", mt.MIME() == "text/plain")
}
Output:

MIME(): application/json
matches: application/json: true
matches: application/*: false
matches: text/plain: false

func (MediaType) Matches added in v1.0.4

func (mediaType MediaType) Matches(mt MediaType) bool

Matches checks whether the MIME media types match handling wildcards in either

Example

ExampleMediaType_Matches comparing only on the MIME media type which must either match exactly or be the wildcard token

package main

import (
	"fmt"

	"github.com/elnormous/contenttype"
)

func main() {
	base := contenttype.NewMediaType("application/json; q=0.01; charset=utf-8")
	noMatch := contenttype.NewMediaType("text/json")
	partialWildcard := contenttype.NewMediaType("application/*")
	fullWildcard := contenttype.NewMediaType("*/*")
	diffParams := contenttype.MediaType{Type: "application", Subtype: "json", Parameters: contenttype.Parameters{"charset": "utf-8"}}
	match := contenttype.MediaType{Type: "application", Subtype: "json"}

	fmt.Printf("matches exactly: %v\n", base.Matches(base))
	fmt.Printf("matches exactly: %v\n", base.Matches(noMatch))
	fmt.Printf("matches exactly: %v\n", base.Matches(partialWildcard))
	fmt.Printf("matches exactly: %v\n", base.Matches(fullWildcard))
	fmt.Printf("matches exactly: %v\n", base.Matches(diffParams))
	fmt.Printf("matches exactly: %v\n", base.Matches(match))
}
Output:

matches exactly: true
matches exactly: false
matches exactly: true
matches exactly: true
matches exactly: true
matches exactly: true

func (MediaType) MatchesAny added in v1.0.4

func (mediaType MediaType) MatchesAny(mts ...MediaType) bool

MatchesAny checks whether the MIME media types matches any of the specified list of mediatype handling wildcards in any of them

func (*MediaType) String

func (mediaType *MediaType) String() string

Converts the MediaType to string.

type Parameters

type Parameters = map[string]string

Parameters represents media type parameters as a key-value map.

Jump to

Keyboard shortcuts

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