Practice of Programming

プログラム とか Linuxとかの話題

chromium で foxyproxy 相当がないのでHTTP::Proxyで

これで、Firefoxはたまにしか必要なくなった。

#!/usr/bin/perl

use HTTP::Proxy;
use strict;

my $proxy = HTTP::Proxy->new(port => 8080);
$proxy->push_filter(request => MyFilter->new($ARGV[0]));
$proxy->start;

package MyFilter;

use base qw/HTTP::Proxy::HeaderFilter/;
use YAML::Syck qw/LoadFile/;
use strict;

sub new {
  my $class = shift;
  my $self = $class->SUPER::new();
  my $cfg = LoadFile(shift);
  my @subs;
  my %tmp;
  foreach my $p (sort {($tmp{$a} ||= $cfg->{$a}->{priority}) <=> ($tmp{$b} ||= $cfg->{$b}->{priority})} keys %$cfg) {
    my @hosts = @{$cfg->{$p}->{hosts}};
    push @subs,
      sub {
        my $h = shift;
        foreach my $host (@hosts) {
   	  return $p if $h =~ m{$host};
        }
      };
  }
  $self->{__proxy_subs} = \@subs;
  return $self;
}

sub filter {
   my ($self, $headers, $message) = @_;
   my $h = $headers->{host};
   my $subs = $self->{__proxy_subs};

   $ENV{http_proxy} = '';
   foreach my $sub (@$subs) {
     last if $ENV{http_proxy} = $sub->($h);
   }
   $self->proxy->agent->env_proxy();
}

以下のようなYAMLファイル。

---
http://localhost:18080:
  hosts:
    - ^192\.168\.0\.1
    - example\.com\.local
  priority: 0

ファイルが変更されたら読み直しとかしてもいいかもしれない。
複数いけるように書いてますが、僕は一個しか必要ないんでテストしてませぬ。