basic http server
This commit is contained in:
55
srv/main.hy
Normal file
55
srv/main.hy
Normal file
@ -0,0 +1,55 @@
|
||||
(import socket [socket AF_INET SOCK_STREAM SOL_SOCKET SO_REUSEADDR])
|
||||
(import threading [Thread])
|
||||
(import log [log])
|
||||
(import traceback [format-exc])
|
||||
(import http-utils :as http)
|
||||
(import content.router [match-request])
|
||||
|
||||
(require hyrule.control [defmain])
|
||||
|
||||
(setv [ADDRESS PORT] ["127.0.0.1" 5000])
|
||||
|
||||
(defmain []
|
||||
(let [socket (socket AF_INET SOCK_STREAM)]
|
||||
(try
|
||||
(.setsockopt socket SOL_SOCKET SO_REUSEADDR 1)
|
||||
(.bind socket #(ADDRESS PORT))
|
||||
(.listen socket 10)
|
||||
(.debug log "socket bound")
|
||||
|
||||
(while True
|
||||
(try
|
||||
(.start
|
||||
(Thread
|
||||
:target (fn [client-socket address]
|
||||
(try
|
||||
(setv request-data (bytes))
|
||||
(while (setx data (.recv client-socket 1024))
|
||||
(+= request-data data)
|
||||
(when (< (len data) 1024)
|
||||
(break)))
|
||||
|
||||
(setv parsed-request (http.request.parse-data request-data))
|
||||
(.debug log parsed-request)
|
||||
(.info log (+ (str (cond
|
||||
(in "X-Real-IP" (. parsed-request (get "headers"))) (. parsed-request (get "headers") (get "X-Real-IP"))
|
||||
True (get address 0))) f": {(. parsed-request (get "method"))} {(. parsed-request (get "route") (get "path"))}"))
|
||||
|
||||
(setv response (match-request parsed-request))
|
||||
(.sendall client-socket (http.response.send #** response))
|
||||
|
||||
(except [e Exception]
|
||||
(.warn log (format-exc))
|
||||
(.close client-socket))))
|
||||
|
||||
:args #(#* (socket.accept))))
|
||||
|
||||
(except [e Exception]
|
||||
(.warn log (format-exc)))))
|
||||
|
||||
(except [e Exception]
|
||||
(.critical log (format-exc)))
|
||||
|
||||
(finally
|
||||
(.close socket)
|
||||
(.info log "server shut down")))))
|
Reference in New Issue
Block a user