How to write a simple webserver in Erlang?

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), … Read more

How to perform actions periodically with Erlang’s gen_server?

You have two easy alternatives, use timer:send_interval/2 or erlang:send_after/3. send_interval is easier to setup, while send_after (when used in the Erlang module) is more reliable since it is a built-in function, see the Efficiency Guide. Using send_after also ensures that the gen_server process is not overloaded. If you were using the send_interval function you would … Read more

Erlang: what is the difference between “include_lib” and “include”?

The way the documentation describes the difference between include and include_lib is: include_lib is similar to include, but should not point out an absolute file. Instead, the first path component (possibly after variable substitution) is assumed to be the name of an application. Example: -include_lib(“kernel/include/file.hrl”). The code server uses code:lib_dir(kernel) to find the directory of … Read more

How to call a method dynamically in Elixir, by specifying both module and method name?

You can use apply/3 which is just a wrapper around :erlang.apply/3. It simply invokes the given function from the module with an array of arguments. Since you are passing arguments as the module and function names you can use variables. apply(:lists, :nth, [1, [1,2,3]]) apply(module_name, method_name, [1, array]) If you want to understand more about … Read more