httpd(3erl)
π httpd(3erl) π
Erlang Module Definition β okay bestie, this is the manual page, and it's iconic. π
β¨ NAME β¨
httpd β HTTP server API π
πΈ DESCRIPTION πΈ
Okay so httpd is literally an implementation of an HTTP 1.1 compliant web server, as defined in RFC 2616. It gives you web server start options, administrative functions, and an Erlang callback API. Periodt. π
π¦ DATA TYPES π¦
These are the type definitions that are used more than once in this module, bestie:
boolean() = true | false
string() = list of ASCII characters
path() = string() representing a file or a directory path
ip_address() = {N1,N2,N3,N4} % IPv4 | {K1,K2,K3,K4,K5,K6,K7,K8} % IPv6
hostname() = string() representing a host, for example, "foo.bar.com"
property() = atom()
π ERLANG HTTP SERVER SERVICE START/STOP π
Okay so a web server can be configured to start when starting the Inets application, or dynamically in runtime by calling the Inets application API inets:start(httpd, ServiceConfig) or inets:start(httpd, ServiceConfig, How), see inets(3erl). The configuration options, also called properties, are as follows: β¨
π File Properties π
When the web server is started at application start time, the properties are to be fetched from a configuration file that can consist of a regular Erlang property list, that is, [{Option, Value}], where Option = property() and Value = term(), followed by a full stop. If the web server is started dynamically at runtime, a file can still be specified but also the complete property list. π
{proplist_file, path()}β If this property is defined, Inets expects to find all other properties defined in this file. The file must include all properties listed under mandatory properties.
Note: Note support for legacy configuration file with Apache syntax is dropped in OTP-23.
π§ Mandatory Properties π§
{port, integer()}β The port that the HTTP server listen to. If zero is specified as port, an arbitrary available port is picked and functionhttpd:info/2can be used to determine which port was picked. π₯{server_name, string()}β The name of your server, normally a fully qualified domain name.{server_root, path()}β Defines the home directory of the server, where log files, and so on, can be stored. Relative paths specified 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.{profile, atom()}β Used together withbind_addressandportto uniquely identify a HTTP server. This can be useful in a virtualized environment, where there can be more that one server that has the samebind_addressandport. If this property is not explicitly set, it is assumed that thebind_addressandportuniquely identifies 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 byhttpdcannot 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()}}.
{ipfamily, inet | inet6}β Default isinet, 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.
The 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_actions, mod_cgi, 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()}β The number of seconds the server waits for a subsequent request from the client before closing the connection. Default is150.{max_body_size, integer()}β Limits the size of the message body of an HTTP request. Default is no limit.{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()}β 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(3erl).
π 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.
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 generatedprod:"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 level error under 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]}
[{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:
logger:add_handler_filter(default,
inets_httpd,
{fun logger_filters:domain/2,
{log, equal,
[otp, inets, httpd, my_server, error]}}).
{log_format, common | combined}β Defines if access logs are to be written according to the common log format or the extended common log format. The common format is one line looking like this:remotehost rfc931 authuser [date] "request" status bytes.
Here:
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 this: remotehost rfc931 authuser [date] "request" status bytes "referer" "user_agent"
In addition to the earlier:
"referer"β the URL the client was chillin' on right before it requested this one. If we couldn't figure it out, a minus sign-goes in this field. Sorry bestie, no vibes detected."user_agent"β the software the client claims to be. Yes, they could be lying. If it couldn't be determined, again: minus sign-in the field.
This whole thing affects the access logs written by mod_log and mod_disk_log β¨
{error_log_format, pretty | compact}β default ispretty. If a human is gonna read that error log directly,prettyis literally the move π
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().aliaslets documents live in the local file system instead of thedocument_rootlocation. URLs whose path begins with url-path get mapped to local files beginning with directory-filename, like so:
{alias, {"/image", "/ftp/pub/image"}}
So hitting http://your.server.org/image/foo.gif would refer to the file /ftp/pub/image/foo.gif. Iconic π
{re_write, {Re, Replacement}}βRe = string()andReplacement = string().re_writealso lets documents live in the local file system instead ofdocument_root. URLs get rewritten byre:replace/3to produce a path in the local file-system, like:
{re_write, {"^/[~]([^/]+)(.*)$", "/home/\\1/public\\2"}}
So http://your.server.org/~bob/foo.gif would refer to /home/bob/public/foo.gif. Regex girlies rise up π₯
{directory_index, [string()]}βdirectory_indexgives a list of resources to look for when a client requests a directory using a/at the end of the directory name. Each entry depicts the name of a file in the directory. You can give several files, and the server returns the first one it finds. Example:
{directory_index, ["index.html", "welcome.html"]}
So 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 doesn't exist. Fallback queen behavior π
πΈ CGI Properties β Requires mod_cgi
{script_alias, {Alias, RealName}}βAlias = string()andRealName = string(). Same behavior as thealiasproperty, except they also mark the target directory as containing CGI scripts. URLs with a path beginning with url-path get mapped to scripts beginning with directory-filename, e.g.:
{script_alias, {"/cgi-bin/", "/web/cgi-bin/"}}
So http://your.server.org/cgi-bin/foo would make the server run the script /web/cgi-bin/foo. Slay π«Ά
{script_re_write, {Re, Replacement}}βRe = string()andReplacement = string(). Same behavior as there_writeproperty, except they also mark the target directory as containing CGI scripts. URLs with a path beginning with url-path get mapped to scripts beginning with directory-filename, for example:
{script_re_write, {"^/cgi-bin/(\\d+)/", "/web/\\1/cgi-bin/"}}
So http://your.server.org/cgi-bin/17/foo would make the server run the script /web/17/cgi-bin/foo.
{script_nocache, boolean()}β ifscript_nocacheistrue, the HTTP server adds the header fields necessary to stop proxies from caching the page, by default. Generally this is the preferred vibe. Defaults tofalse.{script_timeout, integer()}β the time in seconds the web server waits between each chunk of data from the script. If the CGI script delivers no data before the timeout, the connection to the client gets closed. Default is15. β°{action, {MimeType, CgiScript}}β requiresmod_action:MimeType = string()andCgiScript = string().actionadds an action that activates 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"}}
{script, {Method, CgiScript}}β requiresmod_action:Method = string()andCgiScript = string().scriptadds an action that activates 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"}}
π§ ESI Properties β Requires mod_esi
{erl_script_alias, {URLPath, [AllowedModule]}}βURLPath = string()andAllowedModule = atom().erl_script_aliasmarks all URLs matching url-path as erl scheme scripts. A matching URL gets mapped into a specific module and function, like:
{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 doesn't exist, httpd_example:yahoo/2. And http://your.server.org/cgi-bin/example/other:yahoo would not be allowed to execute. Gatekeeping, but make it secure π
{erl_script_nocache, boolean()}β iferl_script_nocacheistrue, the server adds HTTP header fields preventing proxies from caching the page. Generally a good idea for dynamic content, since the content often varies between each request. Default isfalse.{erl_script_timeout, integer()}βerl_script_timeoutsets the time in seconds the server waits between each chunk of data 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 used to log server errors. If the filename doesn't begin with a slash (/), it's assumed to be relative to theserver_root.{security_log, path()}β defines the filename of the access log file used to log security events. If the filename doesn't begin with a slash (/), it's assumed to be relative to theserver_root.{transfer_log, path()}β defines the filename of the access log file used to log incoming requests. If the filename doesn't begin with a slash (/), it's 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 the deets. If theinternalfile format is used, the log file gets repaired after a crash β but heads up bestie, when a log file is repaired, data can disappear π. When theexternalfile format is used,httpddoes not start if the log file is broken. Default isexternal.{error_disk_log, path()}β defines the filename of the (disk_log(3erl)) error log file used to log server errors. If the filename doesn't begin with a slash (/), it's assumed to be relative to theserver_root.{error_disk_log_size, {MaxBytes, MaxFiles}}βMaxBytes = integer()andMaxFiles = integer(). Defines the properties of the (disk_log(3erl)) error log file. This file is of type wrap log, and max bytes is written to each file and max files is used before the first file is truncated and reused.{security_disk_log, path()}β defines the filename of the (disk_log(3erl)) access log file logging incoming security events, that is, authenticated requests. If the filename doesn't begin with a slash (/), it's assumed to be relative to theserver_root.{security_disk_log_size, {MaxBytes, MaxFiles}}βMaxBytes = integer()andMaxFiles = integer(). Defines the properties of thedisk_log(3erl)access log file. This file is of type wrap log, and max bytes is written to each file and max files is used before the first file is truncated and reused.{transfer_disk_log, path()}β defines the filename of the (disk_log(3erl)) access log file logging incoming requests. If the filename doesn't begin with a slash (/), it's assumed to be relative to theserver_root.{transfer_disk_log_size, {MaxBytes, MaxFiles}}βMaxBytes = integer()andMaxFiles = integer(). Defines the properties of thedisk_log(3erl)access log file. This file is of type wrap log, and max bytes is written to each file and max files is 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]}β defines a set of hosts granted access to a given directory, for example:
{allow_from, ["123.34.56.11", "150.100.23"]}
The host 123.34.56.11 and all machines on the 150.100.23 subnet are allowed access. Come on in π
{deny_from, all | [RegxpHostString]}β defines a set of hosts denied access to a given directory, for example:
{deny_from, ["123.34.56.11", "150.100.23"]}
The host 123.34.56.11 and all machines on the 150.100.23 subnet are not allowed access. Blocked, blocked, blocked π
{auth_type, plain | dets | mnesia}β sets the type of authentication database used for the directory. The key difference between the methods is that dynamic data can be saved when Mnesia and Dets are used.{auth_user_file, path()}β sets the name of a file containing the list of users and passwords for user authentication. The filename can be either absolute or relative to theserver_root. If using theplainstorage method, this file is a plain text file where each line contains a username followed by a colon, followed by the non-encrypted password. If usernames are duplicated, the behavior is undefined. β οΈ
Example:
ragnar:s7Xxv7
edward:wwjau8
If the Dets storage method is used, the user database is maintained by Dets and must not be edited 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 is stored outside the document tree of the web server β if it's placed in the directory that it protects, clients can download it. Bestie. Do not do that. π
{auth_group_file, path()}β sets the filename for the file that holds your user groups for authentication. The filename can be either absolute or relative toserver_root.
If the plain storage method is used, the group file is a plain text file where each line has a group name, then a colon, then the member usernames separated by spaces. It's giving:
group1: bob joe ante
If the Dets storage method is used, 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.
Security bestie: for real, keep auth_group_file stored outside the document tree of the web server. If it's placed in the directory that it protects, clients can download it. π
{auth_name, string()}β sets the name of the authorization realm (auth-domain) for a directory. This string tells the client which username and password to use. Lowkey important for the whole auth vibe.{auth_access_password, string()}β if 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. To secure the authenticating data, the password must be changed after the web server is started. Otherwise it is written in clear text in the configuration file. No cap, change it. π₯{require_user, [string()]}β defines users to grant access to a given directory using a secret password.{require_group, [string()]}β defines users to grant access to a given directory using a secret password. Same exact energy asrequire_user, just for groups.
π Security Properties - Requires mod_security π
{security_directory, {path(), [{property(), term()}]}} β the properties for the security directories are as follows:
{data_file, path()}β name of the security data file. The filename can either be absolute or relative toserver_root. This file is used to store persistent data for modulemod_security.{max_retries, integer()}β specifies the maximum number of attempts to authenticate a user before the user is blocked out. If a user successfully authenticates while blocked, the user receives 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()}β specifies the number of minutes a user is blocked. After this time has passed, the user automatically regains access. Default is60.{fail_expire_time, integer()}β specifies the number of minutes a failed user authentication is remembered. If a user authenticates after this time has passed, the previous failed authentications are forgotten. Default is30.{auth_timeout, integer()}β specifies the number of seconds a successful user authentication is remembered. After this time has passed, the authentication is no longer reported. Default is30.
π EXPORTS π
info(Pid) -> HttpInformation
info(Pid, Properties) -> HttpInformation
Types:
Pid = pid()
Properties = [atom()]
HttpInformation =
[CommonOption] |
[CommunicationOption] |
[ModOption] |
[LimitOption] |
[AdminOption]
CommonOption =
{port, integer() >= 0} |
{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, integer() >= 1 | 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. When called with only the pid, all properties are fetched. When called with a list of specific properties, they are fetched. The available properties are the same as the start options of the server. Slay, all the tea in one call. β¨
Note:Pidis the pid returned frominets:start/[2,3]. Can also be retrieved frominets:services/0andinets:services_info/0, seeinets(3erl).
info(Address, Port) -> HttpInformation
info(Address, Port, Profile) -> HttpInformation
info(Address, Port, Properties) -> HttpInformation
info(Address, Port, Profile, Properties) -> HttpInformation
Types:
Address = inet:ip_address() | any
Port = integer()
Profile = atom()
Properties = [atom()]
Path = file:name_all()
HttpInformation =
[CommonOption] |
[CommunicationOption] |
[ModOption] |
[LimitOption] |
[AdminOption]
CommonOption =
{port, integer() >= 0} |
{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, integer() >= 1 | 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. When called with only Address and Port, all properties are fetched. When called with a list of specific properties, they are fetched. The available properties are the same as the start options of the server. Very demure, very mindful. π
Note: The Address must be the IP address and cannot be the hostname.
reload_config(Config, Mode) -> ok | {error, Reason} | no_return()
Types:
Config = file:name_all() | [{Option, Value}]
Mode = non_disturbing | disturbing | blocked
Option = atom()
Value = Reason = term()
Reloads the HTTP server configuration without restarting the server. Incoming requests are answered with a temporary down message during the reload time. It's giving "brb, rebooting my vibe" but make it config. π
Note: Available properties are the same as the start options of the server, but the propertiesbind_addressandportcannot be changed.
If mode is disturbing, the server is blocked forcefully, all ongoing requests terminates, and the reload starts immediately. If mode is non-disturbing, no new connections are accepted, but ongoing requests are allowed to complete before the reload is done. Choose your fighter wisely. π¦
π¦ ERLANG WEB SERVER API DATA TYPES π¦
Okay bestie, the Erlang web server API data types are giving exactly this:
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 β and yes, we're doing all of them, no skipping:
dataβ type[{InteractionKey,InteractionValue}]; it's used to propagate data between modules. Depicted asinteraction_data()in function type declarations.socket_typeβsocket_type()says whether it's an IP socket or ansslsocket.socketβ the socket, in formatip_commorssl, depending onsocket_type.config_dbβ the config file directives stored as key-value tuples in an ETS table. Depicted asconfig_db()in function type declarations.methodβ type"GET" | "POST" | "HEAD" | "TRACE", that is, the HTTP method. Iconic behavior.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.httpdensures that 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 the POST method.connectionβtrue | false. If set totrue, the connection to the client is a persistent connection and is not closed when the request is served.
π₯ ERLANG WEB SERVER API CALLBACK FUNCTIONS π₯
β¨ EXPORTS β¨
Module:do(ModData)-> {proceed, OldData} | {proceed, NewData} | {break, NewData} | done
Types:
OldData = list()
NewData = [{response,{StatusCode,Body}}]
| [{response,{response,Head,Body}}]
| [{response,{already_sent,Statuscode,Size}}]
StatusCode = integer()
Body = io_list() | nobody | {Fun, Arg}
Head = [HeaderOption]
HeaderOption = {Option, Value} | {code, StatusCode}
Option = accept_ranges | allow
| cache_control | content_MD5
| content_encoding | content_language
| content_length | content_location
| content_range | content_type | date
| etag | expires | last_modified
| location | pragma | retry_after
| server | trailer | transfer_encoding
Value = string()
Fun = fun( Arg ) -> sent| close | Body
Arg = [term()]
When a valid request reaches httpd, it calls do/1 in each module, defined by the configuration option of Module. The function can generate data for other modules or a response that can be sent back to the client.
The field data in ModData is a list. This list is the list returned from the last call to do/1.
Body is the body of the HTTP response that is sent back to the client. An appropriate header is appended to the message. StatusCode is the status code of the response, see 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. 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.
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. If close is returned from the fun, something has gone wrong and the server signals this to the client by closing the connection.
Module:remove(ConfigDB) -> ok | {error, Reason}
Types:
ConfigDB = ets_table()
Reason = term()
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.
Module:store({Option, Value}, Config)-> {ok, {Option, NewValue}} | {error, Reason}
Types:
Line = string()
Option = property()
Config = [{Option, Value}]
Value = term()
Reason = term()
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. This function only needs clauses for the options implemented by this particular callback module.
πΈ ERLANG WEB SERVER API HELP FUNCTIONS πΈ
π EXPORTS π
parse_query(QueryString) -> QueryList | uri_string:error()
Types:
QueryString = string()
QueryList = [{unicode:chardata(), unicode:chardata() | true}]
parse_query/1 parses incoming data to erl and eval scripts (see mod_esi(3erl)) as defined in the standard URL format, that is, '+' becomes 'space' and decoding of hexadecimal characters (%xx).
π SEE ALSO π
RFC 2616, inets(3erl), ssl(3erl).
Okay that's the whole page, bestie! Footer shoutout: Ericsson AB, inets 8.3.1.2, httpd(3erl) β source/version noted π. The date slot is empty in this chunk, so I'm not inventing one, no cap. Byeeeee πβ¨
π¦ where this page comes from
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms