LoginSignup
1
0

More than 5 years have passed since last update.

Hylang で適当にHTTPサーバを立てる(2) (2018年7月現在)

Last updated at Posted at 2018-07-23

前回の続き

Hylang で適当にHTTPサーバを立てる(1) (2018年7月現在)

ハンドラを書こう

SimpleHTTPRequestHandler を書き換えて、適当なテキストを返すようにしてみよう。

BaseHTTPRequestHandler を継承したクラスを書こう

Lisperならお馴染みのクラスの継承。

現在のHylangでは、クラスの宣言は大体こんな感じ。

(defclass <class-name> [<superclass1> <superclass2>]
  <methods>)

これに合わせて BaseHTTP... を継承した EchoHandler なるものを書く(名前は適当につけた。深い意味はない)

(defclass EchoHandler [BaseHTTPRequestHandler]
  (defn do_GET [self]
    (setv content-len (int (.get self.headers "content-length")))
    (setv requestBody (-> (.read self.rfile content-len)
                          (.decode "UTF-8")))
    (print requestBody)
    (.send_response self 200)
    (.send_header self "Content-type" "text/json")
    (.end_headers self)
    (.wfile.write self (.encode "テキスト\n" "utf-8"))))

あとはこれをハンドラに設定して実行するだけ。

全体のコードはこれだけ

(import [http.server [HTTPServer SimpleHTTPRequestHandler BaseHTTPRequestHandler]]
        [urllib.parse [urlparse]]
        json)

(defclass EchoHandler [BaseHTTPRequestHandler]
  (defn do_GET [self]
    (setv content-len (int (.get self.headers "content-length")))
    (setv requestBody (-> (.read self.rfile content-len)
                          (.decode "UTF-8")))
    (print requestBody)
    (.send_response self 200)
    (.send_header self "Content-type" "text/json")
    (.end_headers self)
    (.wfile.write self (.encode "テキスト\n" "utf-8"))))

(setv httpd (HTTPServer (, "localhost" 8887) EchoHandler))

(.serve_forever httpd)

結果

image.png

Bodyに入ったJSONを読んでみよう

リクエストで飛んで来やすいものベスト3には入っているであろうJSONを読んでみる

やっていることは簡単で、飛んできたrequest-bodyに対して json.loads 関数を適用しているだけ。

(import [http.server [HTTPServer SimpleHTTPRequestHandler BaseHTTPRequestHandler]]
        [urllib.parse [urlparse]]
        json)

(defclass EchoHandler [BaseHTTPRequestHandler]
  (defn do_GET [self]
    (setv content-len (int (.get self.headers "content-length")))
    (setv request-body (-> (.read self.rfile content-len)
                          (.decode "UTF-8")))
    (print request-body)
    (setv json-data (.loads json request-body))
    (print json-data)
    (print (. json-data ["type"]))
    (print (. json-data ["params"]))
    (.send_response self 200)
    (.send_header self "Content-type" "text/json")
    (.end_headers self)
    (.wfile.write self (.encode "テキスト\n" "utf-8"))))

(setv httpd (HTTPServer (, "localhost" 8887) EchoHandler))

(.serve_forever httpd)

送ってみたコマンド

curl -H "Content-type: application/json" -X GET -d "{\"type\" : \"message\", \"params\" : \"メッセージ本文\"}" http://localhost:8887/

結果

image.png

次にやること

JSONで値を返す
適当に何かの処理を足してみる
Hylang で適当にHTTPサーバを立てる(3) (2018年7月現在)

1
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
1
0