1 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 // 5 // A class to help filter URLRequest jobs based on the URL of the request 6 // rather than just the scheme. Example usage: 7 // 8 // // Use as an "http" handler. 9 // URLRequest::RegisterProtocolFactory("http", &URLRequestFilter::Factory); 10 // // Add special handling for the URL http://foo.com/ 11 // URLRequestFilter::GetInstance()->AddUrlHandler( 12 // GURL("http://foo.com/"), 13 // &URLRequestCustomJob::Factory); 14 // 15 // If URLRequestFilter::Factory can't find a handle for the request, it passes 16 // it through to URLRequestInetJob::Factory and lets the default network stack 17 // handle it. 18 19 #ifndef NET_URL_REQUEST_URL_REQUEST_FILTER_H_ 20 #define NET_URL_REQUEST_URL_REQUEST_FILTER_H_ 21 22 #include <map> 23 #include <string> 24 25 #include "base/hash_tables.h" 26 #include "net/url_request/url_request.h" 27 28 class GURL; 29 class URLRequestJob; 30 31 class URLRequestFilter { 32 public: 33 // scheme,hostname -> ProtocolFactory 34 typedef std::map<std::pair<std::string, std::string>, 35 URLRequest::ProtocolFactory*> HostnameHandlerMap; 36 typedef base::hash_map<std::string, URLRequest::ProtocolFactory*> 37 UrlHandlerMap; 38 39 // Singleton instance for use. 40 static URLRequestFilter* GetInstance(); 41 42 static URLRequest::ProtocolFactory Factory; 43 44 void AddHostnameHandler(const std::string& scheme, 45 const std::string& hostname, 46 URLRequest::ProtocolFactory* factory); 47 void RemoveHostnameHandler(const std::string& scheme, 48 const std::string& hostname); 49 50 // Returns true if we successfully added the URL handler. This will replace 51 // old handlers for the URL if one existed. 52 bool AddUrlHandler(const GURL& url, URLRequest::ProtocolFactory* factory); 53 54 void RemoveUrlHandler(const GURL& url); 55 56 // Clear all the existing URL handlers and unregister with the 57 // ProtocolFactory. Resets the hit count. 58 void ClearHandlers(); 59 60 // Returns the number of times a handler was used to service a request. hit_count()61 int hit_count() const { return hit_count_; } 62 63 protected: URLRequestFilter()64 URLRequestFilter() : hit_count_(0) { } 65 66 // Helper method that looks up the request in the url_handler_map_. 67 URLRequestJob* FindRequestHandler(URLRequest* request, 68 const std::string& scheme); 69 70 // Maps hostnames to factories. Hostnames take priority over URLs. 71 HostnameHandlerMap hostname_handler_map_; 72 73 // Maps URLs to factories. 74 UrlHandlerMap url_handler_map_; 75 76 int hit_count_; 77 78 private: 79 // Singleton instance. 80 static URLRequestFilter* shared_instance_; 81 82 DISALLOW_EVIL_CONSTRUCTORS(URLRequestFilter); 83 }; 84 85 #endif // NET_URL_REQUEST_URL_REQUEST_FILTER_H_ 86