net
Built-in library for network access
Example usage
Section titled “Example usage”local net = require("@lune/net")local serde = require("@lune/serde")
-- Sending a web requestlocal response = net.request("https://www.google.com")print(response.ok)print(response.statusCode, response.statusMessage)print(response.headers)
-- Using a JSON web APIlocal response = net.request({ url = "https://dummyjson.com/products/add", method = "POST", headers = { ["Content-Type"] = "application/json" }, body = serde.encode("json", { title = "Cool Pencil", })})local product = serde.decode("json", response.body)print(product.id, "-", product.title)
-- Starting up an http servernet.serve(8080, function(request) return { status = 200, body = "Echo:\n" .. request.body, }end)
-- Writing to a plain TCP streamlocal conn = net.tcp.connect("example.com", 80)
conn:write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")Properties
Section titled “Properties”TCP primitives for the net library
Provides low-level TCP socket functionality for creating custom network
protocols or communicating with services that don’t use HTTP - for all
HTTP usage, please use the request and serve HTTP functions instead.
HTTP primitives for the net library
Provides the request and serve functions for sending HTTP requests and
creating HTTP servers.
Web socket primitives for the net library
Provides the connect function for connecting to web socket servers.
Functions
Section titled “Functions”tcp.connect
Section titled “tcp.connect”function tcp.connect(host: string, port: number, config: (true | TcpConfig)?): TcpStreamConnects to the given host and port, returning a TcpStream.
For additional details, see the documentation for the TcpConfig and TcpStream types.
Will throw an error if the connection fails.
Parameters
host- The host to connect to, either a DNS name or IP addressport- The port to connect toconfig- The optional configuration to use for the stream
Returns
- A connected TcpStream ready for reading and writing
http.request
Section titled “http.request”function http.request(config: string | FetchParams): FetchResponseSends an HTTP request using the given url and / or parameters, and returns a dictionary that describes the response received.
Only throws an error if a miscellaneous network or I/O error occurs, never for unsuccessful status codes.
Parameters
config- The URL or request config to use
Returns
- A dictionary representing the response for the request
http.serve
Section titled “http.serve”function http.serve(port: number, handlerOrConfig: ServeHttpHandler | ServeConfig): ServeHandleCreates an HTTP server that listens on the given port.
This will not block and will keep listening for requests on the given port
until the stop method on the returned ServeHandle has been called.
Parameters
port- The port to use for the serverhandlerOrConfig- The handler function or config to use for the server
ws.connect
Section titled “ws.connect”function ws.connect(url: string): WebSocketConnects to a web socket at the given URL.
Throws an error if the server at the given URL does not support web sockets, or if a miscellaneous network or I/O error occurs.
Parameters
url- The URL to connect to
Returns
- A web socket handle
request
Section titled “request”function net.request(config: string | FetchParams): FetchResponseSends an HTTP request using the given url and / or parameters, and returns a dictionary that describes the response received.
Only throws an error if a miscellaneous network or I/O error occurs, never for unsuccessful status codes.
Parameters
config- The URL or request config to use
Returns
- A dictionary representing the response for the request
socket
Section titled “socket”function net.socket(url: string): WebSocketmust_use
Connects to a web socket at the given URL.
Throws an error if the server at the given URL does not support web sockets, or if a miscellaneous network or I/O error occurs.
Parameters
url- The URL to connect to
Returns
- A web socket handle
function net.serve(port: number, handlerOrConfig: ServeHttpHandler | ServeConfig): ServeHandleCreates an HTTP server that listens on the given port.
This will not block and will keep listening for requests on the given port
until the stop function on the returned ServeHandle has been called.
Parameters
port- The port to use for the serverhandlerOrConfig- The handler function or config to use for the server
urlEncode
Section titled “urlEncode”function net.urlEncode(s: string, binary: boolean?): stringmust_use
Encodes the given string using URL encoding.
Parameters
s- The string to encodebinary- If the string should be treated as binary data and/or is not valid utf-8. Defaults to false
Returns
- The encoded string
urlDecode
Section titled “urlDecode”function net.urlDecode(s: string, binary: boolean?): stringmust_use
Decodes the given string using URL decoding.
Parameters
s- The string to decodebinary- If the string should be treated as binary data and/or is not valid utf-8. Defaults to false
Returns
- The decoded string
FetchParamsOptions
Section titled “FetchParamsOptions”export type FetchParamsOptions = { decompress: boolean?,}Extra options for FetchParams.
This is a dictionary that may contain one or more of the following values:
decompress- If the request body should be automatically decompressed when possible. Defaults totrue
FetchParams
Section titled “FetchParams”export type FetchParams = { url: string, method: HttpMethod?, body: (string | buffer)?, query: HttpQueryMap?, headers: HttpHeaderMap?, options: FetchParamsOptions?,}Parameters for sending network requests with net.request.
This is a dictionary that may contain one or more of the following values:
url- The URL to send a request to. This is always requiredmethod- The HTTP method verb, such as"GET","POST","PATCH","PUT", or"DELETE". Defaults to"GET"body- The request bodyquery- A table of key-value pairs representing query parameters in the request pathheaders- A table of key-value pairs representing headersoptions- Extra options for things such as automatic decompression of response bodies
FetchResponse
Section titled “FetchResponse”export type FetchResponse = { ok: boolean, statusCode: number, statusMessage: string, headers: HttpHeaderMap, body: string,}Response type for sending network requests with net.request.
This is a dictionary containing the following values:
ok- If the status code is a canonical success status code, meaning within the range 200 -> 299statusCode- The status code returned for the requeststatusMessage- The canonical status message for the returned status code, such as"Not Found"for status code 404headers- A table of key-value pairs representing headersbody- The request body, or an empty string if one was not given
tostring on a response gives its status, such as "404 Not Found".
ServeRequest
Section titled “ServeRequest”export type ServeRequest = { path: string, query: { [string]: string? }, method: HttpMethod, headers: { [string]: string }, body: string,}Data type for requests in net.serve.
This is a dictionary containing the following values:
path- The path being requested, relative to the root. Will be/if not specifiedquery- A table of key-value pairs representing query parameters in the request pathmethod- The HTTP method verb, such as"GET","POST","PATCH","PUT", or"DELETE". Will always be uppercaseheaders- A table of key-value pairs representing headersbody- The request body, or an empty string if one was not given
tostring on a request gives its method and path, such as "GET /some/path".
ServeResponse
Section titled “ServeResponse”export type ServeResponse = { status: number?, headers: { [string]: string }?, body: (string | buffer)?,}Response type for requests in net.serve.
This is a dictionary that may contain one or more of the following values:
status- The status code for the request, in the range100->599. Will be200if not specifiedheaders- A table of key-value pairs representing headersbody- The response body
ServeConfig
Section titled “ServeConfig”export type ServeConfig = { address: string?, handleRequest: ServeHttpHandler?, handleWebSocket: ServeWebSocketHandler?,}Configuration for net.serve.
This may contain one of or more of the following values:
addressfor setting the IP address to serve from. Defaults to the loopback interface (http://localhost).handleRequestfor handling normal http requests, equivalent to just passing a function tonet.servehandleWebSocketfor handling web socket requests, which will receive aWebSocketobject as its first and only parameter
When setting address, the handleRequest callback must also be defined.
Example Usage
net.serve(8080, { address = "http://0.0.0.0", handleRequest = function(request) return { status = 200, body = "Echo:\n" .. request.body, } end})ServeHandle
Section titled “ServeHandle”export type ServeHandle = { ip: string, port: number, stop: (self: ServeHandle) -> (),}A handle to a currently running web server.
This contains the following values:
ip- The IP address that the web server is listening onport- The port that the web server is listening onstop- A method to gracefully shut down the web server
WebSocket
Section titled “WebSocket”export type WebSocket = { closeCode: number?, close: (self: WebSocket, code: number?) -> (), send: (self: WebSocket, message: (string | buffer)?, asBinaryMessage: boolean?) -> (), next: (self: WebSocket) -> string?,}A reference to a web socket connection.
The web socket may be in either an “open” or a “closed” state, changing its current behavior.
When open:
- Any function on the socket such as
send,nextorclosecan be called without erroring nextcan be called to yield until the next message is received or the socket becomes closed
When closed:
nextwill no longer return any message(s) and instead instantly return nilsendwill throw an error stating that the socket has been closed
Once the websocket has been closed, closeCode will no longer be nil, and will be populated with a close
code according to the WebSocket specification.
This will be an integer between 1000 and 4999, where 1000 is the canonical code for normal, error-free closure.
TcpConfig
Section titled “TcpConfig”export type TcpConfig = { --[=[ Whether or not to use TLS encryption.
Defaults to `false`. ]=] tls: boolean?, --[=[ The TTL to use for packets sent over the socket. ]=] ttl: number?,}Configuration options for a TCP stream.
Example Usage
-- Plain TCP connectionlocal stream = net.tcp.connect("example.com", 80)
-- TLS connection (shorthand)local stream = net.tcp.connect("example.com", 443, true)
-- TLS connection (explicit config)local stream = net.tcp.connect("example.com", 443, { tls = true })
-- Connection with custom TTLlocal stream = net.tcp.connect("192.168.1.100", 8080, { tls = false, ttl = 128})TcpStream
Section titled “TcpStream”export type TcpStream = { --[=[ The local IP address of the socket, if any. ]=] localIp: string?, --[=[ The local port of the socket, if any. ]=] localPort: number?, --[=[ The remote IP address of the socket, if any. ]=] remoteIp: string?, --[=[ The remote port of the socket, if any. ]=] remotePort: number?, --[=[ Closes the underlying I/O for the stream.
Any writes will throw an error after this method is called. ]=] close: (self: TcpStream) -> (), --[=[ Writes the given data to the stream.
- If the stream is closed, this will throw an error. ]=] write: (self: TcpStream, data: string | buffer) -> (), --[=[ Reads data from the stream, returning a string up to the given `size`.
- If there is no data to read, this will yield until data is available. - If the stream is closed, this will return `nil`. ]=] read: (self: TcpStream, size: number?) -> string?,}A plain TCP stream, which may also be backed by a TLS connection.
Example Usage
local net = require("@lune/net")
local conn = net.tcp.connect("example.com", 80)
conn:write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
local response = conn:read()print(response)
conn:close()