test_server.py 2.3 KB

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