From 86841f61907e8c8b2380f8adfee7466c64c5ac0e Mon Sep 17 00:00:00 2001 From: Ethan Ruszanowski Date: Tue, 23 Jul 2024 17:05:48 -0400 Subject: [PATCH] Add echo body function --- src/webtest.gleam | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/webtest.gleam b/src/webtest.gleam index e2d3528..21558c8 100644 --- a/src/webtest.gleam +++ b/src/webtest.gleam @@ -1,3 +1,4 @@ +import gleam/bit_array import gleam/bytes_builder import gleam/erlang/process import gleam/http @@ -29,6 +30,11 @@ pub fn main() { on_close: fn(_state) { io.println("Goodbye!") }, handler: handle_we_message, ) + ["echo"] -> echo_body(req) + ["chunk"] -> serve_chunk(req) + ["file", ..rest] -> serve_file(req, rest) + ["form"] -> handle_form(req) + _ -> not_found } } @@ -60,3 +66,21 @@ fn handle_we_message(state, conn, message) { mist.Closed | mist.Shutdown -> actor.Stop(process.Normal) } } + +fn echo_body(request: Request(Connection)) -> Response(ResponseData) { + let content_type = + request + |> request.get_header("content-type") + |> result.unwrap("test/plain") + + mist.read_body(request, 1024 * 1024 * 10) + |> result.map(fn(req) { + response.new(200) + |> response.set_body(mist.Bytes(bytes_builder.from_bit_array(req.body))) + |> response.set_header("content-type", content_type) + }) + |> result.lazy_unwrap(fn() { + response.new(400) + |> response.set_body(mist.Bytes(bytes_builder.new())) + }) +}