0
0

503を返すモック用Webサーバーの立ち上げ

Posted at

「503エラーのテストしたいのですが、何か方法思いつきませんか」と質問されたので。
(おそらく何かしらのAPIを提供しているサーバーがエラーを返したときを想定しているのかな、と推測)。

API叩くツール等でモックサーバーを提供していると思われるのでそれを利用する、
AWSのアカウント等があるならロードバランサーを立ち上げる、
などいろいろな解決方法はあるかと思いますが、取り急ぎかつローカルでの検証であればpythonで十分かなーと単に503を返す標準ライブラリで起動できるサーバーをお勧めしました。
nodejsやRuby等でも同じことはできますが、仕事用の端末に入ってないのでPythonで。

from http.server import HTTPServer, BaseHTTPRequestHandler

class My503Handler(BaseHTTPRequestHandler): # BaseHTTPReuqestHanderに基本的な部品がある
    def do_GET(self): # do_GETでGETメソッドがハンドリングできる
        self.protocol_version = 'HTTP/1.1'
        self.send_response(500, '')
        self.send_header('Content-Type', 'text/html')
        self.send_header('Content-Length', '0') # 説明を読む限り'HTTP/1.1`であれば必須のよう
        self.end_headers()

HTTPServer(('localhost', 8000), My503Handler).serve_forever() # HTTPServerの起動

ただ、これ止めてもポートを掴んじゃっている気がします。serve_forever が問題なのか。。。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0