You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The version=1 part of the media-type is a parameter as defined by RFC7231 Section 3.1.1.1. After reviewing several existing different options for parsing the Accept: header, I noticed a disturbing trend: header.split(','). Because parameters may contain quoted strings which contain commas, this is clearly not an appropriate way to parse the header.
I am concerned about correctness, security and performance. As such, I implemented this gem to provide a simple high level interface for both parsing and correctly interpreting these headers.
Installation
Add this line to your application's Gemfile:
gem'http-accept'
And then execute:
$ bundle
Or install it yourself as:
$ gem install http-accept
You can then require it in your code like so:
require'http/accept'
Usage
Here are some examples of how to parse various headers.
Normally, you'd want to match the media types against some set of available mime types:
moduleToJSONdefcontent_typeHTTP::Accept::ContentType.new("application","json",charset: 'utf-8')end# Used for inserting into map.defsplit(*args)content_type.split(*args)enddefconvert(object,options)object.to_jsonendendmoduleToXML# Are you kidding?endmap=HTTP::Accept::MediaTypes::Map.newmap << ToJSONmap << ToXMLobject,media_range=map.for(media_types)content=object.convert(model,media_range.parameters)response=[200,{'Content-Type'=>object.content_type},[content]]
Parsing Accept-Language: headers
You can parse the incoming Accept-Language: header:
Normally, you'd want to match the languages against some set of available localizations:
available_localizations=HTTP::Accept::Languages::Locales.new(["en-nz","en-us"])# Given the languages that the user wants, and the localizations available, compute the set of desired localizations.desired_localizations=available_localizations & languages
The desired_localizations in the example above is a subset of available_localizations.
Create your feature branch (git checkout -b my-new-feature).
Commit your changes (git commit -am 'Add some feature').
Push to the branch (git push origin my-new-feature).
Create new Pull Request.
Developer Certificate of Origin
This project uses the Developer Certificate of Origin. All contributors to this project must agree to this document to have their contributions accepted.
Contributor Covenant
This project is governed by the Contributor Covenant. All contributors and participants agree to abide by its terms.
About
Parse Accept and Accept-Language HTTP headers in Ruby.