Created
May 5, 2018 14:44
-
-
Save airled/d219edac14eee2050dce0ef181640103 to your computer and use it in GitHub Desktop.
Simple HTTP header parser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule HeaderReader do | |
| def read(conn) do | |
| {:ok,headers} = Agent.start_link(fn -> %{} end) | |
| init_line = :gen_tcp.recv(conn, 0) | |
| do_read(headers, conn, :gen_tcp.recv(conn, 0)) | |
| end | |
| defp do_read(headers, conn, {:ok, "\r\n"}) do | |
| IO.inspect Agent.get headers, fn state -> state end | |
| :gen_tcp.close conn | |
| end | |
| defp do_read(headers, conn, {:ok, line}) do | |
| [name, value] = line |> String.trim() |> String.split(": ", parts: 2) | |
| Agent.update(headers, fn state -> Map.put(state, name, value) end) | |
| IO.inspect line | |
| do_read(headers, conn, :gen_tcp.recv(conn, 0)) | |
| end | |
| end | |
| {:ok, conn} = :gen_tcp.connect('178.172.160.2', 80, [:binary, packet: :line, active: false]) | |
| :gen_tcp.send(conn, "GET / HTTP/1.0\n\n") | |
| HeaderReader.read(conn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment