-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreading_body.gleam
More file actions
48 lines (43 loc) · 1.41 KB
/
reading_body.gleam
File metadata and controls
48 lines (43 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import ewe.{type Request, type Response}
import gleam/erlang/process
import gleam/http/request
import gleam/http/response
import gleam/result
import logging
pub fn main() {
logging.configure()
logging.set_level(logging.Info)
// An echo server that reads the request body and sends it back.
//
let assert Ok(_) =
ewe.new(handler)
|> ewe.bind("0.0.0.0")
|> ewe.listening(port: 8080)
|> ewe.start
process.sleep_forever()
}
fn handler(req: Request) -> Response {
// Preserve the original content-type from the request to send back.
//
let content_type =
request.get_header(req, "content-type")
|> result.unwrap("application/octet-stream")
// Read the entire request body into memory with a 10KB limit. This blocks
// until the full body is received. For large uploads or streaming data,
// use ewe.stream_body() instead.
//
case ewe.read_body(req, 10_240) {
Ok(req) ->
response.new(200)
|> response.set_header("content-type", content_type)
|> response.set_body(ewe.BitsData(req.body))
Error(ewe.BodyTooLarge) ->
response.new(413)
|> response.set_header("content-type", "text/plain; charset=utf-8")
|> response.set_body(ewe.TextData("Body too large"))
Error(ewe.InvalidBody) ->
response.new(400)
|> response.set_header("content-type", "text/plain; charset=utf-8")
|> response.set_body(ewe.TextData("Invalid request"))
}
}