Skip to content

Commit

Permalink
post requests
Browse files Browse the repository at this point in the history
  • Loading branch information
hexisdylan committed Jul 23, 2022
1 parent a2b8f9b commit b534ae7
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 8 deletions.
6 changes: 5 additions & 1 deletion lib/conv.ex
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
defmodule Servy.Conv do
defstruct method: "", path: "", resp_body: "", status: nil
defstruct method: "",
path: "",
params: %{},
resp_body: "",
status: nil

def full_status(conv) do
"#{conv.status} #{status_reason(conv.status)}"
Expand Down
25 changes: 25 additions & 0 deletions lib/handler.ex
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ defmodule Servy.Handler do
%{conv | status: 200, resp_body: "Bear #{id}"}
end

# name=Baloo&type=Brown
def route(%Conv{method: "POST", path: "/bears"} = conv) do
params = %{"name" => "Baloo", "type" => "Brown"}

%{
conv
| status: 201,
resp_body: "Created a #{conv.params["type"]} bear named #{conv.params["name"]}"
}
end

# def route(%Conv{method: "GET", path: "/about"} = conv) do
# Path.expand("../pages", __DIR__)
# |> Path.join("about.html")
Expand Down Expand Up @@ -140,3 +151,17 @@ Accept: */*

response = Servy.Handler.handle(request)
IO.puts(response)

request = """
POST /bears HTTP/1.1
Host: example.com
User-Agent: ExampleBrowser/1.0
Accept: */*
Content-Type: application/x-www-form-urlencoded
Content-Length: 21
name=Baloo&type=Brown
"""

response = Servy.Handler.handle(request)
IO.puts(response)
22 changes: 16 additions & 6 deletions lib/parser.ex
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,22 @@ defmodule Servy.Parser do
alias Servy.Conv

def parse(request) do
[method, path, _] =
request
|> String.split("\n")
|> List.first()
|> String.split(" ")
[top, params_string] = String.split(request, "\n\n")

%Conv{method: method, path: path}
[request_line | header_lines] = String.split(top, "\n")

[method, path, _] = String.split(request_line, " ")

params = parse_params(params_string)

%Conv{
method: method,
path: path,
params: params
}
end

def parse_params(params_string) do
params_string |> String.trim() |> URI.decode_query()
end
end
2 changes: 1 addition & 1 deletion lib/plugins.ex
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
defmodule Servy.Plugins do
alias Servy.Conv
alias Servy.Conv, as: Conv
@doc "Logs 404 requests"
def track(%{status: 404, path: path} = conv) do
IO.puts("Warning: #{path} is on the loose!")
Expand Down

0 comments on commit b534ae7

Please sign in to comment.