我从Akamai的日志文件中获取URI,其中包含以下条目: /foo/jim/jam/foo/jim/jam?/foo/./jim/jam/foo/bar/../jim/jam/foo/jim/jam?autho=randomstringfile=jam 我想根据规则将所有这些规范化为相同的条目: 如果有查
/foo/jim/jam /foo/jim/jam? /foo/./jim/jam /foo/bar/../jim/jam /foo/jim/jam?autho=<randomstring>&file=jam
我想根据规则将所有这些规范化为相同的条目:
>如果有查询字符串,请从中删除autho和file.
>如果查询字符串为空,请删除尾随?.
>应删除./的目录条目.
>应删除< fulldir> /../的目录条目.
我原以为Ruby的URI
库会覆盖这个,但是:
>它不提供任何解析查询字符串部分的机制. (这不是很难做到的,也不是标准的.)
>它不会删除尾随?如果查询字符串被清空.
URI.parse('/foo?jim').tap{ |u| u.query='' }.to_s #=> "/foo?"
> normalize方法不会清理.或..在路径中.
因此,如果没有官方图书馆,我发现自己编写了一个基于正则表达式的解决方案.
def normalize(path) result = path.dup path.sub! /(?<=\?).+$/ do |query| query.split('&').reject do |kv| %w[ autho file ].include?(kv[/^[^=]+/]) end.join('&') end path.sub! /\?$/, '' path.sub!(/^[^?]+/){ |path| path.gsub(%r{[^/]+/\.\.},'').gsub('/./','/') } end
它恰好适用于我上面列出的测试用例,但有450,000个清理路径我无法全部检查它们.
>考虑到可能的日志文件条目,上面是否有任何明显的错误?
>有没有更好的方法来实现相同的解析技术,而不是我的手卷正则表达式?
require 'addressable/uri' # normalize relative paths uri = Addressable::URI.parse('http://example.com/foo/bar/../jim/jam') puts uri.normalize.to_s #=> "http://example.com/foo/jim/jam" # removes trailing ? uri = Addressable::URI.parse('http://example.com/foo/jim/jam?') puts uri.normalize.to_s #=> "http://example.com/foo/jim/jam" # leaves empty parameters alone uri = Addressable::URI.parse('http://example.com/foo/jim/jam?jim') puts uri.normalize.to_s #=> "http://example.com/foo/jim/jam?jim" # remove specific query parameters uri = Addressable::URI.parse('http://example.com/foo/jim/jam?autho=<randomstring>&file=jam') cleaned_query = uri.query_values cleaned_query.delete('autho') cleaned_query.delete('file') uri.query_values = cleaned_query uri.normalize.to_s #=> "http://example.com/foo/jim/jam"