-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttpserver.erl
More file actions
29 lines (25 loc) · 760 Bytes
/
httpserver.erl
File metadata and controls
29 lines (25 loc) · 760 Bytes
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
%%
%% Tiny webserver always answer Hello World
%% listen on port speficied when starting it
%%
%% start :
%% httpserver:start(port)
%%
-module(httpserver).
-export([start/1]).
start(Port) ->
spawn(fun () -> {ok, Sock} = gen_tcp:listen(Port, [{active, false}]),
loop(Sock) end).
loop(Sock) ->
{ok, Conn} = gen_tcp:accept(Sock),
Handler = spawn(fun () -> handle(Conn) end),
gen_tcp:controlling_process(Conn, Handler),
loop(Sock).
handle(Conn) ->
gen_tcp:send(Conn, response("Hello World")),
gen_tcp:close(Conn).
response(Str) ->
B = iolist_to_binary(Str),
iolist_to_binary(
io_lib:fwrite("HTTP/1.0 200 OK\nContent-Type: text/html\nContent-Length: ~p\n\n~s",
[size(B), B])).