httpd(3)
β¨ httpd β¨
okay bestie, welcome to httpd(3), the Erlang Module Definition for the HTTP server API π this is part 1 of 5, so buckle up, hydrate, and let's get into it π«Ά
πΈ NAME πΈ
httpd β HTTP server API π
π¦ DESCRIPTION π¦
It's an implementation of an HTTP 1.1 compliant web server, exactly as defined in RFC 2616 β¨. It hands you web server start options, administrative functions, and an Erlang callback API. No cap, that's the whole vibe π
π Data types π
These are the type definitions that show up more than once in this module, so like, learn them once and you're set π :
boolean() = true | falsestring/0 = list of ASCII characterspath() = string() representing a file or a directory pathip_address() = {N1,N2,N3,N4} % IPv4 | {K1,K2,K3,K4,K5,K6,K7,K8} % IPv6hostname() = string() representing a host, for example, "foo.bar.com"property() = atom()
π HTTP server service start & stop π
A web server can be configured to start when you start the Inets application, or dynamically at runtime by calling the Inets application API like inets:start(httpd, ServiceConfig) or inets:start(httpd, ServiceConfig, How) β see inets for that π. The configuration options, which we also call properties, go like this:
πΈ File Properties πΈ
When the web server starts at application start time, the properties get fetched from a configuration file. That file can be a regular Erlang property list, that is, [{Option, Value}], where Option = property() and Value = term(), followed by a full stop. And if the web server is started dynamically at runtime, you can still specify a file, but you can also just hand over the complete property list, no biggie β¨
{proplist_file, path()}β If this property is defined, Inets expects to find all the other properties defined in this file. The file must include all properties listed under mandatory properties, or it's not gonna slay.
NOTE: support for the legacy configuration file with Apache syntax is dropped in OTP-23. it's giving deprecated, bestie, let it go π
π₯ Mandatory Properties π₯
These ones are literally not optional, periodt:
{port, integer()}β The port that the HTTP server listens to. If you specifyzeroas the port, an arbitrary available port gets picked, and thenhttpd:info/2can be used to figure out which port it actually chose π{server_root, path()}β Defines the home directory of the server, where log files and so on can be stored. Relative paths you specify in other properties refer to this directory πΈ{document_root, path()}β Defines the top directory for the documents that are available on the HTTP server π
π¦ Communication Properties π¦
{bind_address, ip_address() | hostname() | any}β Default isany{server_name, string()}β The name of your server, normally a fully qualified domain name.
If it's not given, this defaults to net_adm:localhost().
{profile, atom()}β Used together withbind_addressandportto uniquely identify a HTTP server. This is useful in a virtualized environment, where there can be more than one server that has the samebind_addressandport. If this property is not explicitly set, it is assumed that thebind_addressandportuniquely identify the HTTP server π{socket_type, ip_comm | {ip_comm, Config::proplist()} | {ssl, Config::proplist()}}β Forip_commconfiguration options, seegen_tcp:listen/2; some options that are used internally by httpd cannot be set.
For SSL configuration options, see ssl:listen/2.
Default is ip_comm.
NOTE: OTP-25 deprecates the communication properties{socket_type, ip_comm | {ip_comm, Config::proplist()} | {essl, Config::proplist()}}, replacing it by{socket_type, ip_comm | {ip_comm, Config::proplist()} | {ssl, Config::proplist()}}. so like,esslis old news, move on β¨
{ipfamily, inet | inet6}β Default isinet. The legacy optioninet6fb4no longer makes sense and will be translated toinetπ{minimum_bytes_per_second, integer()}β If given, sets a minimum of bytes per second value for connections.
If the value is unreached, the socket closes for that connection.
This option is good for reducing the risk of "slow DoS" attacks π‘οΈ
π Erlang Web Server API Modules π
{modules, [atom()]}β Defines which modules the HTTP server uses when handling requests. Default is[mod_alias, mod_auth, mod_esi, mod_dir, mod_get, mod_head, mod_log, mod_disk_log]. Notice that some mod-modules are dependent on others, so the order cannot be entirely arbitrary. See the Inets Web Server Modules in the User's Guide for details π
π Limit properties π
{customize, atom()}β A callback module to customize the inets HTTP servers behaviour, seehttpd_custom_api{disable_chunked_transfer_encoding_send, boolean()}β Allows you to disable chunked transfer-encoding when sending a response to an HTTP/1.1 client. Default isfalse.{keep_alive, boolean()}β Instructs the server whether to use persistent connections when the client claims to be HTTP/1.1 compliant. Default istrue.{keep_alive_timeout, integer() | infinity}β The number of seconds the server waits for a subsequent request from the client before closing the connection. This timer covers the waiting time for the request to arrive, starting from the connection opening or the moment the server sent a response to a previous request. Default is150seconds β³{max_body_size, integer() | nolimit}β Limits the size of the message body of an HTTP request. Default is no limit.{request_timeout, pos_integer() | infinity}β Limits the time the server is allowed to be idle waiting for the next chunk of an HTTP request. Refreshes on every incoming chunk within the same request. Default is60seconds.{max_clients, integer()}β Limits the number of simultaneous requests that can be supported. Default is150.{max_header_size, integer()}β Limits the size of the message header of an HTTP request. Default is10240.{max_content_length, integer()}β Maximum content-length in an incoming request, in bytes. Requests with content larger than this are answered with status413. Default is100000000(100 MB).{max_uri_size, integer() | nolimit}β Limits the size of the HTTP request URI. Default is no limit.{max_keep_alive_request, integer()}β The number of requests that a client can do on one connection. When the server has responded to the number of requests defined bymax_keep_alive_requests, the server closes the connection. The server closes it even if there are queued request. Default is no limit.{max_client_body_chunk, integer()}β Enforces chunking of a HTTP PUT or POST body data to be delivered to themod_esicallback. Note this is not supported formod_cgi. Default is no limit, e.i the whole body is delivered as one entity, which could be very memory consuming.mod_esi.
π Administrative Properties π
{mime_types, [{MimeType, Extension}] | path()}βMimeType = string()andExtension = string(). Files delivered to the client are MIME typed according to RFC 1590. File suffixes are mapped to MIME types before file delivery. The mapping between file suffixes and MIME types can be specified in the property list.
Mime types can also be read from a file. The file should contain lines in the form MediaType [Extensions...], such as text/html html htm. To configure this, specify the path to it, such as {mime_types, "/etc/mime.types"}.
If unset, conf/mime.types under server_root will be used if it exists, otherwise, the default is [{"html","text/html"},{"htm","text/html"}] π
{mime_type, string()}β When the server is asked to provide a document type that cannot be determined by the MIME Type Settings, the server uses this default type.{server_admin, string()}β Defines the email-address of the server administrator to be included in any error messages returned by the server π§{server_tokens, none|prod|major|minor|minimal|os|full|{private, string()}}β Defines the look of the value of the server header.
Example: Assuming the version of Inets is 5.8.1, the server header string can look as follows for the different values of server-tokens:
none
"" % A Server: header will not be generated
prod
"inets"
major
"inets/5"
minor
"inets/5.8"
minimal
"inets/5.8.1"
os
"inets/5.8.1 (unix)"
full
"inets/5.8.1 (unix/linux) OTP/R15B"
{private, "foo/bar"}
"foo/bar"
By default, the value is as before, that is, minimal.
{logger, Options::list()}β Currently only one option is supported:{error, ServerID::atom()}Produces logger events on logger levelerrorunder the hierarchical logger domain:[otp, inets, httpd, ServerID, error]. The built in logger formatting function produces log entries from the error reports:
#{server_name => string()
protocol => internal | 'TCP' | 'TLS' | 'HTTP',
transport => "TCP" | "TLS", %% Present when protocol = 'HTTP'
uri => string(), %% Present when protocol = 'HTTP' and URI is valid
peer => inet:peername(),
host => inet:hostname(),
reason => term()
}
An example of a log entry with only default settings of logger
=ERROR REPORT==== 9-Oct-2019::09:33:27.350235 ===
Server: My Server
Protocol: HTTP
Transport: TLS
URI: /not_there
Host: 127.0.1.1:80
Peer: 127.0.0.1:45253
Reason: [{statuscode,404},{description,"Object Not Found"}]
Using this option makes mod_log and mod_disk_log error logs redundant.
Add the filter
{fun logger_filters:domain/2,
{log,equal,[otp,inets, httpd, ServerID, error]}
to appropriate logger handler to handle the events. For example to write the error log from an httpd server with a ServerID of my_server to a file you can use the following sys.config:
[{kernel,
[{logger,
[{handler, http_error_test, logger_std_h,
#{config => #{ file => "log/http_error.log" },
filters => [{inets_httpd, {fun logger_filters:domain/2,
{log, equal,
[otp, inets, httpd, my_server, error]
}}}],
filter_default => stop }}]}]}].
or if you want to add it to the default logger via an API:
{log_format, common | combined}β tells the server whether access logs get written in the common log format or the extended common log format. π
The common format is literally one line that looks like this:
remotehost rfc931 authuser [date] "request" status bytes
and breaking down every single field bestie:
remotehostβ Remote.rfc931β The remote username of the client (RFC 931).authuserβ The username used for authentication.[date]β Date and time of the request (RFC 1123)."request"β The request line as it came from the client (RFC 1945).statusβ The HTTP status code returned to the client (RFC 1945).bytesβ The content-length of the document transferred.
The combined format is one line looking like:
remotehost rfc931 authuser [date] "request" status bytes "referer" "user_agent"
and on top of everything above, you also get:
"referer"β The URL the client was on before requesting the URL (if it could not be determined, a minus sign is placed in this field)."user_agent"β The software the client claims to be using (if it could not be determined, a minus sign is placed in this field).
This affects the access logs written by mod_log and mod_disk_log. no cap. β¨
{error_log_format, pretty | compact}β Default ispretty. If the error log is meant to be read directly by a human,prettyis the best option. π
pretty has a format corresponding to:
io:format("[~s] ~s, reason: ~n ~p ~n~n", [Date, Msg, Reason]).
compact has a format corresponding to:
io:format("[~s] ~s, reason: ~w ~n", [Date, Msg, Reason]).
This affects the error logs written by mod_log and mod_disk_log.
πΈ URL Aliasing Properties - Requires mod_alias πΈ
{alias, {Alias, RealName}}βAlias=string()andRealName=string().aliasallows documents to be stored in the local file system instead of thedocument_rootlocation. URLs with a path beginning withurl-pathis mapped to local files beginning withdirectory-filename, for example:
{alias, {"/image", "/ftp/pub/image"}}
Access to http://your.server.org/image/foo.gif would refer to the file /ftp/pub/image/foo.gif. iconic behavior tbh. π¦
{re_write, {Re, Replacement}}βRe=string()andReplacement=string().re_writeallows documents to be stored in the local file system instead of thedocument_rootlocation. URLs are rewritten byre:replace/3to produce a path in the local file-system, for example:
{re_write, {"^/[~]([^/]+)(.*)$", "/home/\\1/public\\2"}}
Access to http://your.server.org/~bob/foo.gif would refer to the file /home/bob/public/foo.gif. regex girlies rise π§
{directory_index, [string()]}βdirectory_indexspecifies a list of resources to look for if a client requests a directory using a/at the end of the directory name.filedepicts the name of a file in the directory. Several files can be given, in which case the server returns the first it finds, for example:
{directory_index, ["index.html", "welcome.html"]}
Access to http://your.server.org/docs/ would return http://your.server.org/docs/index.html or http://your.server.org/docs/welcome.html if index.html does not exist. π
π CGI Properties - Requires mod_cgi π
NOTE:mod_cgiandmod_actionsare deprecated since OTP 29 and will be removed in OTP 30. Usemod_esiinstead for dynamic page generation. fr fr do not build new stuff on these bestie π
{script_alias, {Alias, RealName}}βAlias=string()andRealName=string(). Have the same behavior as propertyalias, except that they also mark the target directory as containing CGI scripts. URLs with a path beginning withurl-pathare mapped to scripts beginning withdirectory-filename, for example:
{script_alias, {"/cgi-bin/", "/web/cgi-bin/"}}
Access to http://your.server.org/cgi-bin/foo would cause the server to run the script /web/cgi-bin/foo.
NOTE: When usingscript_aliaswith directory-based authentication (seedirectory), ensure that authentication rules reference the actual filesystem path (RealName), not the URL path (Alias). The server correctly resolvesscript_aliaspaths for authentication checks. π
{script_re_write, {Re, Replacement}}βRe=string()andReplacement=string(). Have the same behavior as propertyre_write, except that they also mark the target directory as containing CGI scripts. URLs with a path beginning withurl-pathare mapped to scripts beginning withdirectory-filename, for example:
{script_re_write, {"^/cgi-bin/(\\d+)/", "/web/\\1/cgi-bin/"}}
Access to http://your.server.org/cgi-bin/17/foo would cause the server to run the script /web/17/cgi-bin/foo.
{script_nocache, boolean()}β Ifscript_nocacheis set totrue, the HTTP server by default adds the header fields necessary to prevent proxies from caching the page. Generally this is preferred. Default tofalse.{script_timeout, integer()}β The time in seconds the web server waits between each chunk of data from the script. If the CGI script does not deliver any data before the timeout, the connection to the client is closed. Default is15. β°{action, {MimeType, CgiScript}}- requiresmod_actionsβMimeType=string()andCgiScript=string().actionadds an action activating a CGI script whenever a file of a certain MIME type is requested. It propagates the URL and file path of the requested document using the standard CGIPATH_INFOandPATH_TRANSLATEDenvironment variables.
Example:
{action, {"text/plain", "/cgi-bin/log_and_deliver_text"}}
NOTE:mod_cgiandmod_actionsare deprecated since OTP 29 and will be removed in OTP 30. Usemod_esiinstead for dynamic page generation. π
{script, {Method, CgiScript}}- requiresmod_actionsβMethod=string()andCgiScript=string().scriptadds an action activating a CGI script whenever a file is requested using a certain HTTP method. The method is eitherGETorPOST, as defined in RFC 1945. It propagates the URL and file path of the requested document using the standard CGIPATH_INFOandPATH_TRANSLATEDenvironment variables.
Example:
{script, {"PUT", "/cgi-bin/put"}}
NOTE:mod_cgiandmod_actionsare deprecated since OTP 29 and will be removed in OTP 30. Usemod_esiinstead for dynamic page generation. (yes again bestie, they really want u to know π)
β¨ ESI Properties - Requires mod_esi β¨
{erl_script_alias, {URLPath, [AllowedModule]}}βURLPath=string()andAllowedModule=atom().erl_script_aliasmarks all URLs matchingurl-pathas erl scheme scripts. A matching URL is mapped into a specific module and function, for example:
{erl_script_alias, {"/cgi-bin/example", [httpd_example]}}
A request to http://your.server.org/cgi-bin/example/httpd_example:yahoo would refer to httpd_example:yahoo/3 or, if that does not exist, httpd_example:yahoo/2 and http://your.server.org/cgi-bin/example/other:yahoo would not be allowed to execute. gatekeeping at its finest πͺ
{erl_script_nocache, boolean()}β Iferl_script_nocacheis set totrue, the server adds HTTP header fields preventing proxies from caching the page. This is generally a good idea for dynamic content, as the content often varies between each request. Default isfalse.{erl_script_timeout, integer()}β Iferl_script_timeoutsets the time in seconds the server waits between each chunk of data to be delivered throughmod_esi:deliver/2. Default is15. This is only relevant for scripts that use the erl scheme.
π Log Properties - Requires mod_log π
{error_log, path()}β Defines the filename of the error log file to be used to log server errors. If the filename does not begin with a slash (/), it is assumed to be relative to theserver_root.{security_log, path()}β Defines the filename of the access log file to be used to log security events. If the filename does not begin with a slash (/), it is assumed to be relative to theserver_root.{transfer_log, path()}β Defines the filename of the access log file to be used to log incoming requests. If the filename does not begin with a slash (/), it is assumed to be relative to theserver_root.
π Disk Log Properties - Requires mod_disk_log π
{disk_log_format, internal | external}β Defines the file format of the log files. Seedisk_logfor details. If the internal file format is used, the log file is repaired after a crash. When a log file is repaired, data can disappear. When the external file format is used,httpddoes not start if the log file is broken. Default isexternal.
heads up bestie: withinternal, data can literally vanish on repair. withexternal, a broken log file meanshttpdwill not start at all. pick your chaos πΈ
{error_disk_log, path()}β Defines the filename of the (disk_log) error log file to be used to log server errors. If the filename does not begin with a slash (/), it is assumed to be relative to theserver_root.{error_disk_log_size, {MaxBytes, MaxFiles}}βMaxBytes=integer()andMaxFiles=integer(). Defines the properties of the (disk_log) error log file. This file is of type wrap log andmax bytesis written to each file andmax filesis used before the first file is truncated and reused.{security_disk_log, path()}β Defines the filename of the (disk_log) access log file logging incoming security events, that is, authenticated requests. If the filename does not begin with a slash (/), it is assumed to be relative to theserver_root.{security_disk_log_size, {MaxBytes, MaxFiles}}βMaxBytes=integer()andMaxFiles=integer(). Defines the properties of thedisk_logaccess log file. This file is of type wrap log andmax bytesis written to each file andmax filesis used before the first file is truncated and reused.{transfer_disk_log, path()}β Defines the filename of the (disk_log) access log file logging incoming requests. If the filename does not begin with a slash (/), it is assumed to be relative to theserver_root.{transfer_disk_log_size, {MaxBytes, MaxFiles}}βMaxBytes=integer()andMaxFiles=integer(). Defines the properties of thedisk_logaccess log file. This file is of type wrap log andmax bytesis written to each file andmax filesis used before the first file is truncated and reused. π
π Authentication Properties - Requires mod_auth π
{directory, {path(), [{property(), term()}]}}
The properties for directories are as follows: π
{allow_from, all | [RegxpHostString]}β lists the hosts that are allowed to get into a given directory, like a lil VIP list bestie. Example:
{allow_from, ["123.34.56.11", "150.100.23"]}
so the host 123.34.56.11 and every single machine on the 150.100.23 subnet get the green light. ποΈ
{deny_from, all | [RegxpHostString]}β the opposite energy: names the hosts that are not allowed into a given directory. Example:
{deny_from, ["123.34.56.11", "150.100.23"]}
so the host 123.34.56.11 and all machines on the 150.100.23 subnet are locked out. π«
{auth_type, plain | dets | mnesia}β picks which authentication database this directory uses. The big difference between the methods: dynamic data can actually be saved when you use Mnesia and Dets. β¨{auth_user_file, path()}β names the file holding the user + password list for user auth. The filename can be absolute or relative to theserver_root. If you're on theplainstorage method, this file is a plain text file where each line is a username, then a colon, then the non-encrypted password. If usernames get duplicated, the behavior is undefined (so like, don't π).
Example:
ragnar:s7Xxv7
edward:wwjau8
If you're on the Dets storage method instead, the user database is maintained by Dets and you must not edit it by hand β use the API functions in module mod_auth to create/edit the user database. This directive is ignored if the Mnesia storage method is used. And for security reasons, make sure auth_user_file lives outside the document tree of the web server β because if it's sitting in the very directory it protects, clients can just download it. π
{auth_group_file, path()}β names the file holding the user group list for user auth. The filename can be absolute or relative to theserver_root. On theplainstorage method, the group file is a plain text file where each line is a group name, then a colon, then the members' usernames separated by spaces.
Example:
group1: bob joe ante
If you're using the Dets storage method, the group database is maintained by Dets and must not be edited by hand β use the API for module mod_auth to create/edit the group database. This directive is ignored if the Mnesia storage method is used. And for security reasons, make sure auth_group_file is stored outside the document tree of the web server. If it's in the directory it protects, clients can download it. π
{auth_name, string()}β sets the name of the authorization realm (auth-domain) for a directory. This string is basically the heads-up to the client about which username and password to use. πͺͺ{auth_access_password, string()}β if this is set to anything other than"NoPassword", the password is required for all API calls. If the password is set to"DummyPassword", it must be changed before any other API calls happen. To secure the authenticating data, you have to change the password after the web server is started β otherwise it gets written in clear text in the configuration file. π{require_user, [string()]}β defines the users granted access to a given directory using a secret password. π€«{require_group, [string()]}β defines the users granted access to a given directory using a secret password. π―
π Security Properties β Requires mod_security
{security_directory, {path(), [{property(), term()}]}}
The properties for the security directories are as follows:
{data_file, path()}β the name of the security data file. The filename can be absolute or relative to theserver_root. This file stores persistent data for modulemod_security. πΎ{max_retries, integer()}β how many attempts at authenticating a user are allowed before that user gets blocked out. If a user successfully authenticates while blocked, they get a403(Forbidden) response from the server. If the user makes a failed attempt while blocked, the server returns401(Unauthorized) β for security reasons. Default is3. Can be set toinfinity. π₯{block_time, integer()}β how many minutes a user stays blocked. Once that time has passed, the user automatically regains access. Default is60. β³{fail_expire_time, integer()}β how many minutes a failed user authentication is remembered for. If a user authenticates after this time has passed, the previous failed authentications are forgotten (clean slate, love that for them β¨). Default is30.{auth_timeout, integer()}β how many seconds a successful user authentication is remembered. After this time has passed, the authentication is no longer reported. Default is30.
π οΈ Web server API data types
The Erlang web server API data types are as follows:
ModData = #mod{}
-record(mod, {
data = [],
socket_type = ip_comm,
socket,
config_db,
method,
absolute_uri,
request_uri,
http_version,
request_line,
parsed_header = [],
entity_body,
connection
}).
To access the record in your callback-module use:
-include_lib("inets/include/httpd.hrl").
The fields of record mod have the following meaning:
dataβ type[{InteractionKey,InteractionValue}], used to propagate data between modules. Depictedinteraction_data()in function type declarations. π«±π«²socket_typeβsocket_type()indicates whether it's an IP socket or an ssl socket.socketβ the socket, in formatip_commorssl, depending onsocket_type. πconfig_dbβ the config file directives stored as key-value tuples in an ETS table. Depictedconfig_db()in function type declarations.methodβ type"GET" | "POST" | "HEAD" | "TRACE", that is, the HTTP method.absolute_uriβ if the request is an HTTP/1.1 request, the URI can be in the absolute URI format. In that case,httpdsaves the absolute URI in this field. An example of an absolute URI is"http://ServerName:Part/cgi-bin/find.pl?person=jocke".request_uriβ the Request-URI as defined in RFC 1945, for example,"/cgi-bin/find.pl?person=jocke".http_versionβ the HTTP version of the request, that is,"HTTP/1.0", or"HTTP/1.1".request_lineβ the Request-Line as defined in RFC 1945, for example,"GET /cgi-bin/find.pl?person=jocke HTTP/1.0".parsed_headerβ type[{HeaderKey,HeaderValue}].parsed_headercontains all HTTP header fields from the HTTP request, stored in a list as key-value tuples. See RFC 2616 for a listing of all header fields. For example, the date field is stored as{"date","Wed, 15 Oct 1997 14:35:17 GMT"}. RFC 2616 defines that HTTP is a case-insensitive protocol and the header fields can be in lower case or upper case βhttpdmakes sure all header field names are in lower case. πentity_bodyβ the entity-Body as defined in RFC 2616, for example, data sent from a CGI script using thePOSTmethod.connectionβtrue | false. If set totrue, the connection to the client is a persistent connection and is not closed when the request is served. π€
π See also
RFC 2616, inets, ssl
𧬠DATA TYPES
property() :: atom().
socket_type() :: ip_comm | ssl.
β¨ FUNCTIONS β¨
okay bestie, buckle up, this is the part where we actually do stuff π These are the functions you call. No cap, some of these are iconic and one of them is deprecated (we'll get there, I'll be dramatic about it).
πΈ info(Pid, Properties) -> HttpInformation
info(Pid, Properties) -> HttpInformation
when
Pid :: pid(),
Properties :: [atom()],
HttpInformation ::
[CommonOption] |
[CommunicationOption] |
[ModOption] |
[LimitOption] |
[AdminOption],
CommonOption ::
{port, non_neg_integer()} |
{server_name, string()} |
{server_root, Path} |
{document_root, Path},
CommunicationOption ::
{bind_address,
inet:ip_address() | inet:hostname() | any} |
{profile, atom()} |
{socket_type,
ip_comm |
{ip_comm, ssl:tls_option() | gen_tcp:option()} |
{ssl, ssl:tls_option() | gen_tcp:option()}} |
{ipfamily, inet | inet6} |
{minimum_bytes_per_second, integer()},
ModOption :: {modules, atom()},
LimitOption ::
{customize, atom()} |
{disable_chunked_transfer_encoding_send,
boolean()} |
{keep_alive, boolean()} |
{keep_alive_timeout, integer() | infinity} |
{max_body_size, integer()} |
{request_timeout, pos_integer() | infinity} |
{max_clients, integer()} |
{max_header_size, integer()} |
{max_content_length, integer()} |
{max_uri_size, integer()} |
{max_keep_alive_request, integer()} |
{max_client_body_chunk, integer()},
AdminOption ::
{mime_types,
[{MimeType :: string(), Extension :: string()}] |
Path} |
{mime_type, string()} |
{server_admin, string()} |
{server_tokens,
none | prod | major | minor | minimal | os |
full |
{private, string()}} |
{logger, Options :: list()} |
{log_format, common | combined} |
{error_log_format, pretty | compact};
(Address, Port) -> HttpInformation
when
Address :: inet:ip_address(),
Port :: integer(),
Path :: file:name_all(),
HttpInformation ::
[CommonOption] |
[CommunicationOption] |
[ModOption] |
[LimitOption] |
[AdminOption],
CommonOption ::
{port, non_neg_integer()} |
{server_name, string()} |
{server_root, Path} |
{document_root, Path},
CommunicationOption ::
{bind_address,
inet:ip_address() | inet:hostname() | any} |
{profile, atom()} |
{socket_type,
ip_comm |
{ip_comm, ssl:tls_option() | gen_tcp:option()} |
{ssl, ssl:tls_option() | gen_tcp:option()}} |
{ipfamily, inet | inet6} |
{minimum_bytes_per_second, integer()},
ModOption :: {modules, atom()},
LimitOption ::
{customize, atom()} |
{disable_chunked_transfer_encoding_send,
boolean()} |
{keep_alive, boolean()} |
{keep_alive_timeout, integer() | infinity} |
{max_body_size, integer()} |
{request_timeout, pos_integer() | infinity} |
{max_clients, integer()} |
{max_header_size, integer()} |
{max_content_length, integer()} |
{max_uri_size, integer()} |
{max_keep_alive_request, integer()} |
{max_client_body_chunk, integer()},
AdminOption ::
{mime_types,
[{MimeType :: string(), Extension :: string()}] |
Path} |
{mime_type, string()} |
{server_admin, string()} |
{server_tokens,
none | prod | major | minor | minimal | os |
full |
{private, string()}} |
{logger, Options :: list()} |
{log_format, common | combined} |
{error_log_format, pretty | compact}.
Fetches information about the HTTP server. π It's basically the "hey what's your deal rn" function.
- Call it with only the pid and it fetches all the properties. Everything. The whole vibe. No filter, no chill.
- Call it with a list of specific properties and it fetches just those, bestie. Picky, and we love that for you.
The available properties are the same as the start options of the server. Like, literally the same list you'd start it with, so iykyk π«Ά
NOTE:Pidis the pid returned frominets:start/[2,3]. You can also get it frominets:services/0andinets:services_info/0β go seeinetsfor the deets. π
π¦ info(Address, Port, Profile, Properties) -> HttpInformation
info(Address, Port, Profile, Properties) -> HttpInformation
when
Address :: inet:ip_address() | any,
Port :: integer(),
Profile :: atom(),
Properties :: [atom()],
Path :: file:name_all(),
HttpInformation ::
[CommonOption] |
[CommunicationOption] |
[ModOption] |
[LimitOption] |
[AdminOption],
CommonOption ::
{port, non_neg_integer()} |
{server_name, string()} |
{server_root, Path} |
{document_root, Path},
CommunicationOption ::
{bind_address,
inet:ip_address() | inet:hostname() | any} |
{profile, atom()} |
{socket_type,
ip_comm |
{ip_comm, ssl:tls_option() | gen_tcp:option()} |
{ssl, ssl:tls_option() | gen_tcp:option()}} |
{ipfamily, inet | inet6} |
{minimum_bytes_per_second, integer()},
ModOption :: {modules, atom()},
LimitOption ::
{customize, atom()} |
{disable_chunked_transfer_encoding_send,
boolean()} |
{keep_alive, boolean()} |
{keep_alive_timeout, integer() | infinity} |
{max_body_size, integer()} |
{request_timeout, pos_integer() | infinity} |
{max_clients, integer()} |
{max_header_size, integer()} |
{max_content_length, integer()} |
{max_uri_size, integer()} |
{max_keep_alive_request, integer()} |
{max_client_body_chunk, integer()},
AdminOption ::
{mime_types,
[{MimeType :: string(), Extension :: string()}] |
Path} |
{mime_type, string()} |
{server_admin, string()} |
{server_tokens,
none | prod | major | minor | minimal | os |
full |
{private, string()}} |
{logger, Options :: list()} |
{log_format, common | combined} |
{error_log_format, pretty | compact}.
Fetches information about the HTTP server. Same energy, different door π
- Call it with only
AddressandPortand boom, all the properties get fetched. The full tea βοΈ - Call it with a list of specific properties and you get exactly those. Curated. Main character behavior only.
The available properties are, again, the same as the start options of the server. Consistency, periodt. β¨
NOTE: The Address must be the IP address and cannot be the hostname. Like, do not try it with a hostname, it will not go the way you want it to, ngl. π«
π parse_query(QueryString) -> QueryList | uri_string:error()
parse_query(QueryString) -> QueryList | uri_string:error()
when
QueryString :: string(),
QueryList ::
[{unicode:chardata(),
unicode:chardata() | true}].
Deprecated:httpd:parse_query/1is deprecated, bestie β useuri_string:dissect_query/1instead. π It's giving "still here but we don't talk about her".
parse_query/1 parses incoming data to erl and eval scripts (see mod_esi) as defined in the standard URL format. So it's doing the classics:
'+'becomes'space'π- and it decodes hexadecimal characters (
%xx) π’
π reload_config(Config, Mode) -> ok | {error, Reason} | no_return()
reload_config(Config, Mode) -> ok | {error, Reason} | no_return()
when
Config :: file:name_all() | [{Option, Value}],
Mode :: non_disturbing | disturbing | blocked,
Option :: atom(),
Value :: term(),
Reason :: term().
Reloads the HTTP server configuration without restarting the server. β¨ Glow-up in place, no reboot required, we LOVE a transformation arc.
While the reload is happening, incoming requests get answered with a temporary down message during the reload time. So like, hold please, she's changing π
NOTE: Available properties are the same as the start options of the server, but the propertiesbind_addressandportcannot be changed. Those two are locked, no negotiation, that's just the rules. π
And now, the modes β pick your fighter:
disturbingβ the server gets blocked forcefully, all ongoing requests terminate, and the reload starts immediately. Brutal. No survivors. πnon-disturbingβ no new connections are accepted, but ongoing requests are allowed to complete before the reload is done. Gentle queen energy, everyone finishes their sentence first π«Άblockedβ no explanation given for this one, it's just sitting there in the list like π (it's aModevalue, that's all the page says, I'm not making things up for you bestie)
π CALLBACKS π
do(ModData) β¨
okay so when a valid request actually reaches httpd, it calls do/1 in every module, and which modules those are is decided by the configuration option of Module. bestie, this function is where the magic happens: it can generate data for other modules, or generate a response that gets sent straight back to the client. π«Ά
The field data in ModData is a list. Specifically, it's the list returned from the last call to do/1. so it's like the baton being passed around the relay race of your modules πββοΈ
Body is the body of the HTTP response that gets sent back to the client. An appropriate header is appended to the message. π
StatusCode is the status code of the response β go peep RFC 2616 for the appropriate values. π
Head is a key value list of HTTP header fields. The server constructs an HTTP header from this data. See RFC 2616 for the appropriate value for each header field. And listen: if the client is an HTTP/1.0 client, the server filters the list so that only HTTP/1.0 header fields are sent back to the client. no cap, it's doing a whole vibe check on your headers. π
If Body is returned and equal to {Fun,Arg}, the web server tries apply/2 on Fun with Arg as argument. The web server expects that the fun either returns a list (Body) that is an HTTP response, or the atom sent if the HTTP response is sent back to the client. And if close is returned from the fun? π something has gone wrong and the server signals this to the client by closing the connection. literally the server hanging up the phone on them.
NOTE: It is strongly advised to useNewDataFormatin the return value ofdo/1β it relies on a newer mechanism for parsing and sending headers, provides more accurate status codes, and supports a wider range ofBodyformats. bestie please useNewDataFormat, it's giving main character energy and the old way is not it. π
remove(ConfigDB) π
When httpd is shut down, it tries to execute remove/1 in each Erlang web server callback module. The programmer can use this function to clean up resources created in the store function. it's the "okay bye, let me tidy up before I go" function π§Ήβ¨
store/2 π¦
Checks the validity of the configuration options before saving them in the internal database. This function can also have a side effect, that is, setup of necessary extra resources implied by the configuration option. It can also resolve possible dependencies among configuration options by changing the value of the option. And this function only needs clauses for the options implemented by this particular callback module β no need to overcommit, bestie, just do your part. π
and that's a wrap on httpd(3) fr fr π this one's from Ericsson AB, inets 9.7.2, and it's dated httpd(3) β go forth and callback responsibly, you absolute icon πβ¨
π¦ where this page comes from
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms