Imported Upstream version 1.27.0
[platform/upstream/grpc.git] / test / core / http / test_server.py
1 #!/usr/bin/env python2.7
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
17 import argparse
18 import BaseHTTPServer
19 import os
20 import ssl
21 import sys
22
23 _PEM = os.path.abspath(
24     os.path.join(os.path.dirname(sys.argv[0]), '../../..',
25                  'src/core/tsi/test_creds/server1.pem'))
26 _KEY = os.path.abspath(
27     os.path.join(os.path.dirname(sys.argv[0]), '../../..',
28                  'src/core/tsi/test_creds/server1.key'))
29 print _PEM
30 open(_PEM).close()
31
32 argp = argparse.ArgumentParser(description='Server for httpcli_test')
33 argp.add_argument('-p', '--port', default=10080, type=int)
34 argp.add_argument('-s', '--ssl', default=False, action='store_true')
35 args = argp.parse_args()
36
37 print 'server running on port %d' % args.port
38
39
40 class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
41
42     def good(self):
43         self.send_response(200)
44         self.send_header('Content-Type', 'text/html')
45         self.end_headers()
46         self.wfile.write('<html><head><title>Hello world!</title></head>')
47         self.wfile.write('<body><p>This is a test</p></body></html>')
48
49     def do_GET(self):
50         if self.path == '/get':
51             self.good()
52
53     def do_POST(self):
54         content = self.rfile.read(int(self.headers.getheader('content-length')))
55         if self.path == '/post' and content == 'hello':
56             self.good()
57
58
59 httpd = BaseHTTPServer.HTTPServer(('localhost', args.port), Handler)
60 if args.ssl:
61     httpd.socket = ssl.wrap_socket(httpd.socket,
62                                    certfile=_PEM,
63                                    keyfile=_KEY,
64                                    server_side=True)
65 httpd.serve_forever()