A small Janet library to make reading and writing HTTP/1.1 streams easier. With Janet's built-in net library, you can write terse HTTP code without a large framework.
jpm install https://github.com/m7andrew/read-write-http
A minimal server:
(use http)
(def response
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
(defn handler [stream]
(pp (read/request stream))
(write/response stream response)
(net/close stream))
(net/server "localhost" 8000 handler)Send a request:
(use http)
(def request
{:method "GET"
:uri "/imghp"
:headers {"Host" "www.google.com"}})
(def stream (net/connect "www.google.com" 80))
(write/request stream request)
(pp (read/response stream))
(net/close stream)(read/request stream)Reads a stream for a request. Returns a request as a struct with the following fields:
:methodstring, the HTTP method.:pathstring, the URI path.:querystruct, the URI query paramaters. If no query, field is omitted.:headersstruct, the HTTP headers.:bodystring, the request body. If no body, field is omitted.
Returns nil if no request could be read.
(read/response stream)Reads a stream for a response. Returns a response as a struct with the following fields:
:statusnumber, the HTTP status code.:headersstruct, the HTTP headers.:bodystring, the HTTP body. If no body, field is omitted.
Returns nil if no response could be read.
(write/request stream request)Write a request to a stream where request is a struct or table with the following fields:
:methodstring, the HTTP method. Optional. Defaults to"GET".:uristring, the HTTP URI. Optional. Defaults to"/".:headersstruct or table, the HTTP headers."Host"is required.:bodystring, the HTTP body. Optional.
Returns nil, or raises an error if the write failed.
(write/response stream response)Write a response to a stream where response is a struct or table with the following fields:
:statusnumber, the HTTP status code. Optional. Defaults to200:headersstruct or table, the HTTP headers. Optional."Content-Length"is automatically set.:bodystring, the HTTP body. Optional.
Returns nil, or raises an error if the write failed.