An HTTP content negotiator for Go
Thanks to negotiator which is the original version written in javascript.
To install negotiator
, you need to install Go and set your Go workspace first.
The first need Go installed (version 1.11+ is required),
then you can use the below Go command to install negotiator
.
$ go get -u github.com/soongo/negotiator
import "github.com/soongo/negotiator"
// The negotiator constructor receives a http.Header object
negotiator := negotiator.New(header)
availableMediaTypes := []string{"text/html", "text/plain", "application/json"}
// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8'
negotiator.MediaTypes()
// -> ["text/html", "image/jpeg", "application/*"]
negotiator.MediaTypes(availableMediaTypes)
// -> ["text/html", "application/json"]
negotiator.MediaType(availableMediaTypes)
// -> "text/html"
Returns the most preferred media type from the client.
Returns the most preferred media type from a list of available media types.
Returns an array of preferred media types ordered by the client preference.
Returns an array of preferred media types ordered by priority from a list of available media types.
availableLanguages := []string{"en", "es", "fr"}
// Let's say Accept-Language header is 'en;q=0.8, es, pt'
negotiator.Languages()
// -> ["es", "pt", "en"]
negotiator.Languages(availableLanguages)
// -> ["es", "en"]
negotiator.Language(availableLanguages)
// -> "es"
Returns the most preferred language from the client.
Returns the most preferred language from a list of available languages.
Returns an array of preferred languages ordered by the client preference.
Returns an array of preferred languages ordered by priority from a list of available languages.
availableCharsets := []string{"utf-8", "iso-8859-1", "iso-8859-5"}
// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2'
negotiator.Charsets()
// -> ["utf-8", "iso-8859-1", "utf-7"]
negotiator.Charsets(availableCharsets...)
// -> ["utf-8", "iso-8859-1"]
negotiator.Charset(availableCharsets...)
// -> "utf-8"
Returns the most preferred charset from the client.
Returns the most preferred charset from a list of available charsets.
Returns an array of preferred charsets ordered by the client preference.
Returns an array of preferred charsets ordered by priority from a list of available charsets.
availableEncodings := []string{"identity", "gzip"}
// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5'
negotiator.Encodings()
// -> ["gzip", "identity", "compress"]
negotiator.Encodings(availableEncodings...)
// -> ["gzip", "identity"]
negotiator.Encoding(availableEncodings...)
// -> "gzip"
Returns the most preferred encoding from the client.
Returns the most preferred encoding from a list of available encodings.
Returns an array of preferred encodings ordered by the client preference.
Returns an array of preferred encodings ordered by priority from a list of available encodings.