How to write a simple webserver in Erlang?

前端 未结 6 754
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 12:20

Using the default Erlang installation what is the minimum code needed to produce a \"Hello world\" producing web server?

6条回答
  •  忘掉有多难
    2020-12-07 13:08

    Taking "produce" literally, here is a pretty small one. It doesn't even read the request (but does fork on every request, so it's not as minimal possible).

    -module(hello).
    -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])).
    

提交回复
热议问题