xref: /aosp_15_r20/external/cronet/net/test/embedded_test_server/request_handler_util.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef NET_TEST_EMBEDDED_TEST_SERVER_REQUEST_HANDLER_UTIL_H_
6 #define NET_TEST_EMBEDDED_TEST_SERVER_REQUEST_HANDLER_UTIL_H_
7 
8 #include <map>
9 #include <memory>
10 #include <string>
11 #include <vector>
12 
13 #include "base/files/file_path.h"
14 #include "base/strings/string_split.h"
15 #include "net/test/embedded_test_server/embedded_test_server.h"
16 #include "net/test/embedded_test_server/http_response.h"
17 
18 class GURL;
19 
20 namespace net::test_server {
21 struct HttpRequest;
22 
23 // The extension that is used to find a file containing mock headers to use
24 // for a test file. For example, a test data directory can have:
25 //   foo.html
26 //   foo.html.mock-http-headers
27 // When the test server serves foo.html, if it finds foo.html.mock-http-headers
28 // it will use the contents of that file for the headers.
29 extern const base::FilePath::CharType kMockHttpHeadersExtension[];
30 
31 // Returns the Content-Type header value for a path based on its extension.
32 std::string GetContentType(const base::FilePath& path);
33 
34 // This file is only meant for compatibility with testserver.py. No
35 // additional handlers should be added here that don't affect multiple
36 // distinct tests.
37 
38 using RequestQuery = std::map<std::string, std::vector<std::string>>;
39 
40 // Return whether |request| starts with a URL path of |url|.
41 bool ShouldHandle(const HttpRequest& request, const std::string& prefix_path);
42 
43 // Calls |handler| if the |request| URL starts with |prefix|.
44 std::unique_ptr<HttpResponse> HandlePrefixedRequest(
45     const std::string& prefix,
46     const EmbeddedTestServer::HandleRequestCallback& handler,
47     const HttpRequest& request);
48 
49 // Parses |url| to get the query and places it into a map.
50 RequestQuery ParseQuery(const GURL& url);
51 
52 // Returns a path that serves the contents of the file at |original_path|
53 // with all the text matching the elements of |text_to_replace| replaced
54 // with the corresponding values. The path is returned in |replacement_path|.
55 // The result path is only usable by HandleFileRequest which will perform the
56 // actual replacements of the file contents.
57 std::string GetFilePathWithReplacements(
58     const std::string& original_path,
59     const base::StringPairs& text_to_replace);
60 
61 // Handles |request| by serving a file from under |server_root|.
62 std::unique_ptr<HttpResponse> HandleFileRequest(
63     const base::FilePath& server_root,
64     const HttpRequest& request);
65 
66 }  // namespace net::test_server
67 
68 #endif  // NET_TEST_EMBEDDED_TEST_SERVER_REQUEST_HANDLER_UTIL_H_
69