Parsing URIs that have curly braces, URI::InvalidURIError: bad URI(is not URI?)

后端 未结 2 1848
小蘑菇
小蘑菇 2021-01-14 06:39

Using ruby 1.9.2-p290. I came across an issue trying to parse a URI like the following:

require \'uri\'
my_uri = \"http://www.anyserver.com/getdata?anyparame         


        
2条回答
  •  春和景丽
    2021-01-14 07:40

    # Need to not fail when uri contains curly braces
    # This overrides the DEFAULT_PARSER with the UNRESERVED key, including '{' and '}'
    # DEFAULT_PARSER is used everywhere, so its better to override it once
    module URI
      remove_const :DEFAULT_PARSER
      unreserved = REGEXP::PATTERN::UNRESERVED
      DEFAULT_PARSER = Parser.new(:UNRESERVED => unreserved + "\{\}")
    end
    

    Following up the same issue, since DEFAULT_PARSER is used everywhere, its better to substitute it completely insted of just for the URI#parse method. Additionally this avoids allocating memory for the instantiation of a new Parser object every time.

提交回复
热议问题