-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsending_response.gleam
More file actions
58 lines (53 loc) · 1.61 KB
/
sending_response.gleam
File metadata and controls
58 lines (53 loc) · 1.61 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
49
50
51
52
53
54
55
56
57
58
import ewe.{type Connection, type ResponseBody}
import gleam/crypto
import gleam/erlang/process
import gleam/http/request.{type Request}
import gleam/http/response.{type Response}
import gleam/int
import gleam/result
import logging
pub fn main() {
logging.configure()
logging.set_level(logging.Info)
// A server demonstrating different response body types and path routing.
//
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(Connection)) -> Response(ResponseBody) {
// Pattern match on path segments for cleaner routing.
// Example: "/hello/alice" becomes ["hello", "alice"]
//
case request.path_segments(req) {
["hello", name] -> {
// Here, we will use TextData for text responses.
//
response.new(200)
|> response.set_header("content-type", "text/plain; charset=utf-8")
|> response.set_body(ewe.TextData("Hello, " <> name <> "!"))
}
["bytes", amount] -> {
// Use BitsData for binary responses. We generate random bytes
// to demonstrate sending binary data.
//
let body =
int.parse(amount)
|> result.unwrap(0)
|> crypto.strong_random_bytes
|> ewe.BitsData
response.new(200)
|> response.set_header("content-type", "application/octet-stream")
|> response.set_body(body)
}
_ ->
// Use Empty for responses with no body (like 404, 204, etc).
// You don't need to set content-type for empty bodies.
//
response.new(404)
|> response.set_body(ewe.Empty)
}
}