Blog Details

Linux 作業系統 cutexyz > Blog > 未分類 > Python http code 20261003

Python http code 20261003

from http.server import BaseHTTPRequestHandler, HTTPServer

# 設定伺服器監聽的 Host 與 Port
HOST = "localhost"
PORT = 8080


class SimpleHandler(BaseHTTPRequestHandler):

  def do_GET(self):
    # 設定回應狀態碼為 200 (OK)
    self.send_response(200)

    # 設定回應標頭 (Header) 為 HTML 格式
    self.send_header("Content-type", "text/html; charset=utf-8")
    self.end_headers()

    # 準備要回傳的 HTML 內容,body 內只有一個 <h1> 標籤
    html_content = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <title>Simple Server</title>
        </head>
        <body>
            <h1>XXXXXXX</h1>
        </body>
        </html>
        """

    # 將 HTML 內容寫入回應中 (需轉為 bytes)
    self.wfile.write(html_content.encode("utf-8"))


def run():
  server_address = (HOST, PORT)
  httpd = HTTPServer(server_address, SimpleHandler)
  print(f"伺服器已啟動,請開啟瀏覽器訪問: http://{HOST}:{PORT}")
  print("按下 Ctrl + C 可以停止伺服器。")

  try:
    httpd.serve_forever()
  except KeyboardInterrupt:
    pass

  httpd.server_close()
  print("\n伺服器已關閉。")


if __name__ == "__main__":
  run()

Leave A Comment

All fields marked with an asterisk (*) are required