• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# Copyright 2015 gRPC authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Server for httpcli_test"""
16
17import argparse
18from http.server import BaseHTTPRequestHandler
19from http.server import HTTPServer
20import os
21import ssl
22import sys
23
24_PEM = os.path.abspath(
25    os.path.join(
26        os.path.dirname(sys.argv[0]),
27        "../../..",
28        "src/core/tsi/test_creds/server1.pem",
29    )
30)
31_KEY = os.path.abspath(
32    os.path.join(
33        os.path.dirname(sys.argv[0]),
34        "../../..",
35        "src/core/tsi/test_creds/server1.key",
36    )
37)
38print(_PEM)
39open(_PEM).close()
40
41argp = argparse.ArgumentParser(description="Server for httpcli_test")
42argp.add_argument("-p", "--port", default=10080, type=int)
43argp.add_argument("-s", "--ssl", default=False, action="store_true")
44args = argp.parse_args()
45
46print("server running on port %d" % args.port)
47
48
49class Handler(BaseHTTPRequestHandler):
50    def good(self):
51        self.send_response(200)
52        self.send_header("Content-Type", "text/html")
53        self.end_headers()
54        self.wfile.write(
55            "<html><head><title>Hello world!</title></head>".encode("ascii")
56        )
57        self.wfile.write(
58            "<body><p>This is a test</p></body></html>".encode("ascii")
59        )
60
61    def do_GET(self):
62        if self.path == "/get":
63            self.good()
64
65    def do_POST(self):
66        content_len = self.headers.get("content-length")
67        content = self.rfile.read(int(content_len)).decode("ascii")
68        if self.path == "/post" and content == "hello":
69            self.good()
70
71
72httpd = HTTPServer(("localhost", args.port), Handler)
73if args.ssl:
74    ctx = ssl.SSLContext()
75    ctx.load_cert_chain(certfile=_PEM, keyfile=_KEY)
76    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
77httpd.serve_forever()
78