### Example: Basic Server Setup Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Demonstrates how to create and start an HTTP server that responds with 'Hello, World!' to all requests. Includes cleanup. ```julia using HTTP # Create and start server server = HTTP.listen!("127.0.0.1", 8080) do request return HTTP.Response(200; body = "Hello, World!") end # Server is running in background println("Server running on port 8080") # Cleanup HTTP.forceclose(server) ``` -------------------------------- ### Start HTTP Server and Handle Request/Response with Stream Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md An example demonstrating how to start an HTTP server, read request details (method, target, body) from a stream, and write a custom response back to the client. ```julia using HTTP server = HTTP.serve!("127.0.0.1", 8080) do stream # Read request metadata request = HTTP.startread(stream) println("Method: $(request.method)") println("Target: $(request.target)") # Read request body (if any) body = read(stream, String) # Write response response = HTTP.Response(200; body = "Got: $body") HTTP.write(stream, response) end ``` -------------------------------- ### Quick Start: HTTP.jl Client and Server Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/index.md This snippet demonstrates how to start a local HTTP server, send a GET request to it using the client API, and retrieve the response body. It includes setting up a basic server response and configuring the client request. ```julia using HTTP server = HTTP.serve!("127.0.0.1", 0; listenany = true) do req payload = "hello from HTTP.jl docs" return HTTP.Response( 200; headers = ["Content-Type" => "text/plain"], body = payload, ) end url = "http://127.0.0.1:$(HTTP.port(server))/hello" resp = HTTP.get(url; proxy = HTTP.ProxyConfig()) HTTP.forceclose(server) String(resp.body) ``` -------------------------------- ### listen! (Convenience Overloads) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Convenience functions to create and start a server in a single call, simplifying server setup. They return the running `Server` instance. ```APIDOC ## listen! (Convenience Overloads) ### Description Convenience functions to create and start a server in a single call, simplifying server setup. They return the running `Server` instance. ### Method Signatures 1. `listen!(handler::Function; network::AbstractString="tcp", address::AbstractString="127.0.0.1:0", kwargs...) -> Server` 2. `listen!(handler::Function, port::Integer; kwargs...) -> Server` 3. `listen!(handler::Function, address::AbstractString, port::Integer; kwargs...) -> Server` ### Parameters - `handler` (Function): The request handler function. - `network` (AbstractString, optional): The network type (default: `"tcp"`). - `address` (AbstractString, optional): The bind address (default: `"127.0.0.1:0"`). - `port` (Integer): The port to listen on. - `kwargs...`: Additional keyword arguments passed to the `Server` constructor. ### Returns - `Server`: The running server instance. ### Source `src/http_server.jl:1309-1463` ``` -------------------------------- ### listen! (Server Start) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Starts the HTTP server, enabling it to accept incoming connections. This method is blocking and returns the server instance once started. ```APIDOC ## listen! (Server Start) ### Description Starts the HTTP server, enabling it to accept incoming connections. This method is blocking and returns the server instance once started. ### Method `listen!(server::Server) -> Server` ### Parameters - `server` (Server) - The server instance to start. ### Returns - `Server`: The running server instance. ### Source `src/http_server.jl:1250-1307` ``` -------------------------------- ### Example: Request with Timeouts Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/configuration.md This example demonstrates how to set specific timeouts for a GET request. It includes a connect timeout, an overall request timeout, and a response header timeout. Ensure the `HTTP` package is imported before use. ```julia using HTTP response = HTTP.request( "GET", "https://httpbin.org/delay/2"; connect_timeout = 5.0, # 5 second connect timeout request_timeout = 10.0, # 10 second overall timeout response_header_timeout = 3.0, # 3 second header timeout ) ``` -------------------------------- ### Start an HTTP server and handle requests Source: https://github.com/juliaweb/http.jl/blob/master/README.md Start a basic HTTP server using HTTP.serve! that responds to requests with plain text. Demonstrates how to create a server and make a request to it, then close the server. ```julia using HTTP server = HTTP.serve!("127.0.0.1", 8081) do request payload = "Hello from HTTP.jl" return HTTP.Response( 200; headers = ["Content-Type" => "text/plain"], body = payload, ) end resp = HTTP.get("http://127.0.0.1:8081"; proxy = HTTP.ProxyConfig()) println(resp.status) println(String(resp.body)) HTTP.forceclose(server) ``` -------------------------------- ### listen! Method Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Starts the server and begins accepting connections. The server instance is returned, and it can be stopped using close() or forceclose(). ```julia listen!(server::Server) -> Server ``` -------------------------------- ### Example Streaming Operations Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/client-api.md Shows how to use the `open` function for streaming. Includes an example of streaming a response directly to a file and another for pull-based streaming where the response is read into a string. ```julia using HTTP # Stream response to file open("output.bin", "w") do io HTTP.get("https://example.com/large_file"; response_stream = io) end # Pull-based streaming response = HTTP.open(:GET, "https://example.com/stream") do stream text = String(read(stream)) end ``` -------------------------------- ### Example HTTP Requests Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/client-api.md Demonstrates making POST, PUT, and DELETE requests using the convenience functions. Includes examples for sending string bodies, setting headers, and making simple DELETE calls. ```julia using HTTP # POST with string body HTTP.post("https://httpbin.org/post"; body = "hello world") # PUT with headers HTTP.put("https://api.example.com/resource"; headers = ["Content-Type" => "application/json"], body = "{\"field\": \"value\"}") # DELETE request HTTP.delete("https://api.example.com/resource/123") ``` -------------------------------- ### Install HTTP.jl using Pkg REPL Source: https://github.com/juliaweb/http.jl/blob/master/README.md Install the HTTP.jl package using the Pkg REPL mode. ```julia pkg> add HTTP ``` -------------------------------- ### Set Up an HTTP Server Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/README.md Create a simple HTTP server using `HTTP.listen!`. This example handles requests to `/greet` and returns a 404 for other paths. ```julia using HTTP server = HTTP.listen!("127.0.0.1", 8080) do request if request.target == "/greet" name = HTTP.header(request.headers, "X-Name", "World") return HTTP.Response(200; body = "Hello, $name!") else return HTTP.Response(404; body = "Not Found") end end # Server is running in background println("Server on port $(HTTP.port(server))") # Clean up HTTP.forceclose(server) ``` -------------------------------- ### listen!(handler::Function, port::Integer; kwargs...) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/websockets-api.md A convenience overload for starting a WebSocket server on a specific port. It simplifies server setup when only the port number is needed. ```APIDOC ### listen!(handler::Function, port::Integer; kwargs...) ```julia listen!(handler::Function, port::Integer; kwargs...) -> Server ``` Convenience overload to start a server on a specific port. **Example**: ```julia using HTTP server = HTTP.WebSockets.listen!(8081) do ws for msg in ws println("Received: ", String(msg)) end end ``` ``` -------------------------------- ### Install HTTP.jl using Pkg functions Source: https://github.com/juliaweb/http.jl/blob/master/README.md Install the HTTP.jl package programmatically using Pkg functions. ```julia using Pkg; Pkg.add("HTTP") ``` -------------------------------- ### Convenience listen! Overloads Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Provides simplified functions to create and start a server in a single call, returning the running Server instance. ```julia listen!( handler::Function; network::AbstractString="tcp", address::AbstractString="127.0.0.1:0", kwargs... ) -> Server ``` ```julia listen!(handler::Function, port::Integer; kwargs...) -> Server ``` ```julia listen!( handler::Function, address::AbstractString, port::Integer; kwargs... ) -> Server ``` -------------------------------- ### serve! Method Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Starts a server for manual connection handling, providing handlers with Stream objects for incremental I/O. This is a lower-level API than listen!. ```julia serve!( server::Server, listener; ready::Threads.Event=Threads.Event() ) -> Server ``` -------------------------------- ### Start an HTTP Server with a Stream Handler Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Starts an HTTP server that handles requests incrementally using streams. This is useful for processing large requests or responses without loading everything into memory. ```julia using HTTP # Stream-based handler for incremental reads/writes server = HTTP.serve!("127.0.0.1", 8080) do stream request = HTTP.startread(stream) body = "Received request: $(request.method) $(request.target)" HTTP.setstatus(stream, 200) HTTP.write(stream, body) end HTTP.forceclose(server) ``` -------------------------------- ### serve! (Server Management) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Starts a server with manual connection handling, providing handlers with `Stream` objects for incremental I/O. This is a lower-level interface than `listen!`. ```APIDOC ## serve! (Server Management) ### Description Starts a server with manual connection handling, providing handlers with `Stream` objects for incremental I/O. This is a lower-level interface than `listen!`. ### Method `serve!(server::Server, listener; ready::Threads.Event=Threads.Event()) -> Server` ### Parameters - `server` (Server): The server instance to manage. - `listener`: The listener object for handling connections. - `ready` (Threads.Event, optional): An event to signal when the server is ready. ### Returns - `Server`: The server instance. ### Source `src/http_server.jl:1465-1563` ``` -------------------------------- ### Example: Streaming Data Generator Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Shows how to generate data on-the-fly for a request body using CallbackBody. ```julia using HTTP # Generate data on-the-fly function counting_body() count = Ref(0) read_cb = (dst) -> begin if count[] >= 100 return 0 # EOF end str = "Count: $(count[])\n" count[] += 1 bytes = codeunits(str) n = min(length(dst), length(bytes)) copyto!(dst, 1, bytes, 1, n) return n end close_cb = () -> println("Stream closed") return HTTP.CallbackBody(read_cb, close_cb) end response = HTTP.request( "POST", "http://api.example.com/"; body = counting_body() ) ``` -------------------------------- ### Start WebSocket Server on Specific Port Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/websockets-api.md Start a WebSocket server on a specific port, printing received messages. This is a convenience overload for starting a server. ```julia using HTTP server = HTTP.WebSockets.listen!(8081) do ws for msg in ws println("Received: ", String(msg)) end end ``` -------------------------------- ### Example: Streaming Multiple Sources Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Illustrates creating a streaming body from multiple sequential file sources using CallbackBody. ```julia using HTTP function multi_source_body(sources::Vector{String}) sources_iter = Ref(1) current_file = Ref(nothing) current_offset = Ref(1) read_cb = (dst) -> begin while sources_iter[] <= length(sources) if current_file[] === nothing current_file[] = open(sources[sources_iter[]], "r") current_offset[] = 1 end n = readbytes!(current_file[], dst) if n > 0 return n else close(current_file[]) current_file[] = nothing sources_iter[] += 1 end end return 0 # All sources exhausted end close_cb = () -> begin if current_file[] !== nothing close(current_file[]) end end return HTTP.CallbackBody(read_cb, close_cb) end ``` -------------------------------- ### Complete Chat Application Example Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/websockets-api.md This snippet demonstrates a full-featured chat application using WebSockets in Julia. It includes server-side logic for managing clients and broadcasting messages, as well as a basic client example to connect and interact with the server. ```julia using HTTP using Sockets using Dates # Simple in-memory chat room const chat_clients = Set{HTTP.WebSocket}() const chat_lock = ReentrantLock() function broadcast_message(sender::HTTP.WebSocket, msg::String) lock(chat_lock) try for client in chat_clients if client !== sender try HTTP.WebSockets.send(client, msg) catch # Client disconnected end end end finally unlock(chat_lock) end end function chat_handler(ws::HTTP.WebSocket) # Add client to chat room lock(chat_lock) push!(chat_clients, ws) unlock(chat_lock) try broadcast_message(ws, "[SYSTEM] A user joined. ($(length(chat_clients)) users)") # Listen for messages for msg in ws msg_str = String(msg) timestamp = Dates.format(Dates.now(), "HH:MM:SS") full_msg = "[$timestamp] User: $msg_str" broadcast_message(ws, full_msg) end finally # Remove client when they disconnect lock(chat_lock) delete!(chat_clients, ws) unlock(chat_lock) broadcast_message(ws, "[SYSTEM] A user left. ($(length(chat_clients)) users)") end end # Start server server = HTTP.WebSockets.listen!("127.0.0.1", 8081) println("Chat server running on ws://127.0.0.1:$(HTTP.port(server))") # Example client HTTP.WebSockets.open("ws://127.0.0.1:8081") do ws HTTP.WebSockets.send(ws, "Hello everyone!") for msg in ws println(String(msg)) end end ``` -------------------------------- ### CookieJar Constructor and Usage Example Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/types.md Demonstrates creating a CookieJar and using it with an HTTP.Client to automatically manage cookies during HTTP requests. ```julia using HTTP jar = HTTP.CookieJar() client = HTTP.Client(; cookiejar = jar) # Cookies are automatically stored from Set-Cookie headers HTTP.get(client, "https://example.com/login"; body = "credentials...") # Cookies are automatically included in subsequent requests HTTP.get(client, "https://example.com/authenticated") ``` -------------------------------- ### Start WebSocket Server on Specific Address and Port Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/websockets-api.md Start a WebSocket server on a specific IP address and port, sending a greeting message back to clients. This overload allows specifying both the address and port. ```julia using HTTP server = HTTP.WebSockets.listen!("0.0.0.0", 8081) do ws for msg in ws HTTP.WebSockets.send(ws, "Hello ", String(msg)) end end ``` -------------------------------- ### Example: Streaming Multiple Sources Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Shows how to combine multiple data sources (e.g., files) into a single streaming body. ```APIDOC ## Example: Streaming Multiple Sources ```julia using HTTP function multi_source_body(sources::Vector{String}) sources_iter = Ref(1) current_file = Ref(nothing) current_offset = Ref(1) read_cb = (dst) -> begin while sources_iter[] <= length(sources) if current_file[] === nothing current_file[] = open(sources[sources_iter[]], "r") current_offset[] = 1 end n = readbytes!(current_file[], dst) if n > 0 return n else close(current_file[]) current_file[] = nothing sources_iter[] += 1 end end return 0 # All sources exhausted end close_cb = () -> begin if current_file[] !== nothing close(current_file[]) end end return HTTP.CallbackBody(read_cb, close_cb) end ``` ``` -------------------------------- ### Example: Streaming File Upload Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Demonstrates streaming a large file upload without buffering using CallbackBody. ```julia using HTTP # Stream a file without buffering file_path = "/path/to/large_file.bin" file = open(file_path, "r") body = HTTP.CallbackBody( read_cb = (dst) -> readbytes!(file, dst), close_cb = () -> close(file) ) response = HTTP.request( "POST", "http://api.example.com/upload"; body = body ) ``` -------------------------------- ### Complete Header Workflow Example Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/headers-api.md Demonstrates a full workflow for managing HTTP headers, including creation, access, modification, removal, setting defaults, iteration, and usage in HTTP requests. ```julia using HTTP # Create headers with multiple constructors headers = HTTP.Headers( "Content-Type" => "application/json", "Accept" => "application/json" ) # Access values ct = HTTP.header(headers, "content-type") # case-insensitive all_values = HTTP.headers(headers, "Accept") # Modify HTTP.appendheader(headers, "Accept", "text/plain") # Merges with comma HTTP.setheader(headers, "Cache-Control", "no-cache") # Remove HTTP.removeheader(headers, "Accept") # Set default HTTP.defaultheader!(headers, "User-Agent", "MyApp/1.0") # Iterate for (key, value) in headers println("$key: $value") end # Use with requests response = HTTP.request("GET", "https://api.example.com/"; headers = headers) ``` -------------------------------- ### Example: HTTP.jl Client with Defaults Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/configuration.md Demonstrates creating an HTTP.Client with custom default headers, query parameters, timeouts, and other settings. Shows how per-request options override these defaults. ```julia using HTTP # Create client with sensible defaults client = HTTP.Client(; default_headers = [ "User-Agent" => "MyApp/1.0", "Accept" => "application/json" ], default_query = ["api_key" => "secret123"], connect_timeout = 10.0, # 10 seconds request_timeout = 30.0, # 30 seconds max_redirects = 3, cookiejar = HTTP.CookieJar(), prefer_http2 = true, ) # All requests use these defaults response = HTTP.get(client, "https://api.example.com/users") # Per-request overrides take precedence response = HTTP.get( client, "https://api.example.com/search"; headers = ["Accept" => "text/plain"], # Overrides default query = ["q" => "test"], # Merged with default_query ) ``` -------------------------------- ### WebSocket server and client example Source: https://github.com/juliaweb/http.jl/blob/master/README.md Set up a WebSocket server that echoes messages and a client that sends a message and receives the echo. Includes proxy configuration for the client. ```julia using HTTP server = HTTP.WebSockets.listen!("127.0.0.1", 8081) do ws for msg in ws HTTP.WebSockets.send(ws, msg) end end HTTP.WebSockets.open("ws://127.0.0.1:8081"; proxy = HTTP.ProxyConfig()) do ws HTTP.WebSockets.send(ws, "Hello") println(HTTP.WebSockets.receive(ws)) end HTTP.WebSockets.forceclose(server) ``` -------------------------------- ### Example: Streaming Data Generator Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Illustrates creating a streaming body that generates data on-the-fly, such as a sequence of numbers. ```APIDOC ## Example: Streaming Data Generator ```julia using HTTP # Generate data on-the-fly function counting_body() count = Ref(0) read_cb = (dst) -> begin if count[] >= 100 return 0 # EOF end str = "Count: $(count[])\n" count[] += 1 bytes = codeunits(str) n = min(length(dst), length(bytes)) copyto!(dst, 1, bytes, 1, n) return n end close_cb = () -> println("Stream closed") return HTTP.CallbackBody(read_cb, close_cb) end response = HTTP.request( "POST", "http://api.example.com/"; body = counting_body() ) ``` ``` -------------------------------- ### BytesBody Usage Example Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/types.md Demonstrates how to create and use a BytesBody, including checking its length and reading data into a destination buffer. ```julia using HTTP body = HTTP.BytesBody(b"Hello, World!") println(length(body)) # => 13 dst = UInt8[0, 0, 0, 0, 0] n = HTTP.body_read!(body, dst) println(n) # => 5 println(String(dst)) # => "Hello" println(length(body)) # => 8 (remaining bytes) ``` -------------------------------- ### Start WebSocket Echo Server on Specific Address Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/websockets-api.md Start a WebSocket server that listens on a specific address and port, echoing back all received messages. The server runs in the background and can be cleaned up using `HTTP.forceclose`. ```julia using HTTP # Echo server server = HTTP.WebSockets.listen!("127.0.0.1", 8081) do ws for msg in ws HTTP.WebSockets.send(ws, msg) # Echo back end end # Server is running in background println("Server running on port ", HTTP.port(server)) # Cleanup HTTP.forceclose(server) ``` -------------------------------- ### Example: Reading BytesBody Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Demonstrates how to read data from a BytesBody into a buffer. Shows the number of bytes read and the resulting buffer content. ```julia using HTTP body = HTTP.BytesBody(b"Hello, World!") buffer = UInt8[0, 0, 0, 0, 0] n = HTTP.body_read!(body, buffer) # n == 5, buffer == b"Hello" ``` -------------------------------- ### Make a GET request and print status and body Source: https://github.com/juliaweb/http.jl/blob/master/README.md Perform a simple HTTP GET request and display the response status and body as a string. Note that String(r.body) aliases the buffer; use String(copy(r.body)) to preserve the original bytes. ```julia using HTTP r = HTTP.get("http://httpbin.org/ip") println(r.status) println(String(r.body)) ``` -------------------------------- ### HTTP.get Request (Before) Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/migration-1x.md Shows the 1.x way of making a GET request and reading the entire response body as a string. ```julia resp = HTTP.get(url) text = String(resp.body) ``` -------------------------------- ### Example: Streaming File Upload Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Demonstrates how to stream a large file for upload without buffering the entire file content in memory. ```APIDOC ## Example: Streaming File Upload ```julia using HTTP # Stream a file without buffering file_path = "/path/to/large_file.bin" file = open(file_path, "r") body = HTTP.CallbackBody( read_cb = (dst) -> readbytes!(file, dst), close_cb = () -> close(file) ) response = HTTP.request( "POST", "http://api.example.com/upload"; body = body ) ``` ``` -------------------------------- ### Configure Server with Timeouts and Header Limits Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/configuration.md Starts an HTTP server with custom timeouts for reading, writing, and idle connections, as well as a limit on request header size. ```julia using HTTP # Configure server with request timeouts server = HTTP.listen!( "127.0.0.1", 8080; read_timeout_ns = 30 * 1_000_000_000, # 30 seconds read_header_timeout_ns = 10 * 1_000_000_000, # 10 seconds write_timeout_ns = 30 * 1_000_000_000, # 30 seconds idle_timeout_ns = 5 * 60 * 1_000_000_000, # 5 minutes max_header_bytes = 512 * 1024, # 512 KB max headers ) do request HTTP.Response(200; body = "Hello") end HTTP.forceclose(server) ``` -------------------------------- ### Common Use Case: Chunked Streaming Responses Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Example of setting up a server to send chunked streaming responses using CallbackBody. ```julia server = HTTP.serve!("127.0.0.1", 8080) do stream request = HTTP.startread(stream) body = HTTP.CallbackBody( (dst) -> begin data = fetch_next_chunk() if isempty(data) return 0 end n = min(length(dst), length(data)) copyto!(dst, data[1:n]) return n end, () -> nothing ) HTTP.write(stream, HTTP.Response(200; body = body)) end ``` -------------------------------- ### Making a High-Level HTTP Request Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/client.md Demonstrates using HTTP.request for a GET request with proxy configuration. This is suitable for eager responses. ```julia using HTTP server = HTTP.serve!("127.0.0.1", 0; listenany = true) do req payload = if req.target == "/stream" "streaming response body" else "$(req.method) $(req.target)" end return HTTP.Response( 200; headers = ["Content-Type" => "text/plain"], body = payload, ) end base_url = "http://127.0.0.1:$(HTTP.port(server))" resp = HTTP.request("GET", base_url * "/requests"; proxy = HTTP.ProxyConfig()) HTTP.forceclose(server) (status = resp.status, body = String(resp.body)) ``` -------------------------------- ### listen!(handler::Function; kwargs...) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/websockets-api.md Starts a WebSocket server that listens for incoming connections. The provided handler function is executed for each new connection, managing the communication lifecycle. ```APIDOC ## Server API ### listen!(handler::Function; kwargs...) ```julia listen!( handler::Function; network::AbstractString="tcp", address::AbstractString="127.0.0.1:0", kwargs... ) -> Server ``` Start a WebSocket server. The handler function receives an open `WebSocket` and is responsible for communication. **Parameters**: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `handler` | `Function` | — | Handler function signature: `(ws::WebSocket) -> Nothing`. | | `network` | `AbstractString` | `"tcp"` | Network type (e.g., `"tcp"`). | | `address` | `AbstractString` | `"127.0.0.1:0"` | Bind address as `host:port`. Port `0` selects an available port. | | `...kwargs` | — | — | Additional server options (timeouts, max headers, etc.). | **Returns**: `Server` object. Keep it alive or the server stops. **Example**: ```julia using HTTP # Echo server server = HTTP.WebSockets.listen!("127.0.0.1", 8081) do ws for msg in ws HTTP.WebSockets.send(ws, msg) # Echo back end end # Server is running in background println("Server running on port ", HTTP.port(server)) # Cleanup HTTP.forceclose(server) ``` ``` -------------------------------- ### Common Use Case: Large File Upload Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Example of setting up a CallbackBody for uploading large files without loading them into memory. ```julia file = open("huge_file.bin", "r") body = HTTP.CallbackBody( (dst) -> readbytes!(file, dst), () -> close(file) ) ``` -------------------------------- ### listen!(handler::Function, address::AbstractString, port::Integer; kwargs...) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/websockets-api.md A convenience overload for starting a WebSocket server on a specific network address and port. This allows for more control over the server's network binding. ```APIDOC ### listen!(handler::Function, address::AbstractString, port::Integer; kwargs...) ```julia listen!(handler::Function, address::AbstractString, port::Integer; kwargs...) -> Server ``` Convenience overload to start a server on a specific address and port. **Example**: ```julia using HTTP server = HTTP.WebSockets.listen!("0.0.0.0", 8081) do ws for msg in ws HTTP.WebSockets.send(ws, "Hello ", String(msg)) end end ``` ``` -------------------------------- ### Example of Handling TimeoutError Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/errors.md Shows how to set a deadline for a request using HTTP.RequestContext and catch TimeoutError, printing details about the expired operation. ```julia using HTTP try # 5-second deadline from now ctx = HTTP.RequestContext(deadline_ns = time_ns() + 5_000_000_000) HTTP.request("GET", "https://httpbin.org/delay/10"; context = ctx) catch err if err isa HTTP.TimeoutError println("Timeout during $(err.operation)") println("Budget: $(err.timeout_ns) ns") println("Elapsed: $(err.elapsed_ns) ns") end end ``` -------------------------------- ### Set Comprehensive Timeout Values for HTTP Client Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/configuration.md Configure various timeout settings for a client, including connection, request, response header, and idle timeouts. This example demonstrates setting timeouts in seconds for high-level APIs and includes error handling for timeouts. ```julia using HTTP client = HTTP.Client(; connect_timeout = 10.0, # 10 seconds to connect request_timeout = 60.0, # 60 seconds total response_header_timeout = 15.0, # 15 seconds to get headers read_idle_timeout = 30.0, # 30 seconds idle on reads write_idle_timeout = 30.0, # 30 seconds idle on writes ) # This request respects all timeout limits try response = HTTP.get(client, "https://api.example.com/slow_endpoint") catch err if err isa HTTP.TimeoutError println("Request timed out during $(err.operation)") end end ``` -------------------------------- ### Automatic Response Body Buffering Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md High-level HTTP functions like `request`, `get`, and `post` automatically buffer response bodies into a `Vector{UInt8}`. This example shows how to check the type of the buffered body. ```julia using HTTP response = HTTP.get("https://example.com/") println(typeof(response.body)) # => Vector{UInt8} ``` -------------------------------- ### Handle StatusError in Julia HTTP Client Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/errors.md Demonstrates how to catch and handle a StatusError when making an HTTP GET request. This example shows how to check if an error is an instance of StatusError and access its status and response body. ```julia using HTTP try HTTP.get("http://httpbin.org/status/404"; status_exception = true) catch err if err isa HTTP.StatusError println("HTTP error: $(err.status)") println("Response: $(String(err.response.body))") end end ``` -------------------------------- ### Open and Echo WebSocket Server and Client Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/protocols.md Demonstrates setting up a WebSocket server that echoes messages and a client that connects, sends a message, and receives the echoed reply. Requires the `HTTP.WebSockets` submodule. ```julia using HTTP server = HTTP.WebSockets.listen!("127.0.0.1", 0; listenany = true) do ws for msg in ws HTTP.WebSockets.send(ws, uppercase(String(msg))) end end url = "ws://" * HTTP.WebSockets.server_addr(server) * "/echo" reply = HTTP.WebSockets.open(url; proxy = HTTP.ProxyConfig()) do ws HTTP.WebSockets.send(ws, "hello") HTTP.WebSockets.receive(ws) end HTTP.WebSockets.forceclose(server) reply ``` -------------------------------- ### Perform HTTP GET Request Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/client-api.md Use the `get` function as a convenient shortcut for making HTTP GET requests. It accepts a URL and optional headers, passing additional arguments to the underlying `request` function. ```julia using HTTP response = HTTP.get("https://httpbin.org/get") println(String(response.body)) # With headers response = HTTP.get("https://api.example.com/data"; headers = ["Authorization" => "Bearer token123"]) ``` -------------------------------- ### Tune HTTP/2 Flow-Control Windows Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/protocols.md Adjust the per-stream and connection-level receive windows for HTTP/2 clients and servers using `HTTP2Settings`. Larger windows can improve throughput on high-latency networks. The example sets a 1 MiB per-stream window and a 2 MiB connection window. ```julia using HTTP settings = HTTP.HTTP2Settings( initial_window_size = 1 << 20, # 1 MiB per-stream receive window connection_window_size = 1 << 21, # 2 MiB connection-level receive window ) client = HTTP.Client(http2_settings = settings) server = HTTP.serve!("127.0.0.1", 8080; http2_settings = settings) do request HTTP.Response(200, "ok") end ``` -------------------------------- ### Simple HTTP GET Request Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/api-summary.md Make a basic GET request to a URL. Requires the HTTP package to be imported. ```julia using HTTP response = HTTP.get("https://example.com") ``` -------------------------------- ### Register a GET Route with a Parameter Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/server.md Define a route that matches GET requests to a path with a dynamic parameter. The parameter can be accessed using HTTP.getparam. ```julia using HTTP router = HTTP.Router() HTTP.register!(router, "GET", "/users/{id}") do req id = HTTP.getparam(req, "id") return HTTP.Response(200; body = "user " * id) end server = HTTP.serve!(router, "127.0.0.1", 8080) ``` -------------------------------- ### get(headers, key, default) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/headers-api.md Provides dict-style `get` functionality for headers, returning the first value associated with the key or a specified default value if the header is not found. ```APIDOC ## get(headers, key, default) ### Description Dict-style `get` on `Headers`. Returns the first value for `key`, or `default` if the header is absent. ### Method `get` (dict-style access) ### Parameters #### Path Parameters - **key** (AbstractString) - Required - The header key to retrieve. - **default** - Required - The value to return if the header is absent. ### Response #### Success Response - **value** (String) - The first value for the header key, or the default value. ### Example ```julia using HTTP headers = HTTP.Headers("Content-Type" => "application/json") ct = HTTP.get(headers, "content-type", "") # => "application/json" missing_ct = HTTP.get(headers, "accept", "") # => "" ``` ``` -------------------------------- ### Dict-Style Get for Headers Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/headers-api.md Retrieve header values using a dictionary-style get method. This returns the first value for the specified key, or a provided default value if the header is not found. ```julia get(headers::Headers, key::AbstractString, default) -> String ``` -------------------------------- ### Using Downloads.download (Replacement for HTTP.download) Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/migration-1x.md Shows the recommended way to download a file using the `Downloads` standard library, which replaces the 1.x `HTTP.download` helper. ```julia using Downloads Downloads.download(url, "payload.bin") ``` -------------------------------- ### Configure HTTP Client with Pooling and Defaults Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/README.md Set up an HTTP client with custom default headers, query parameters, timeouts, redirect limits, and a cookie jar. Useful for making repeated requests with consistent settings. ```julia using HTTP client = HTTP.Client(; default_headers = ["User-Agent" => "MyApp/1.0"], default_query = ["api_key" => "secret123"], connect_timeout = 10.0, request_timeout = 30.0, max_redirects = 3, cookiejar = HTTP.CookieJar(), ) response = HTTP.get(client, "https://api.example.com/data") ``` -------------------------------- ### Configure HTTP Server Constructor Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/configuration.md Initializes an HTTP server with various configuration options including network, address, handler, timeouts, and header size limits. ```julia server = HTTP.Server(; network="tcp", address="127.0.0.1:0", handler=handler_function, stream=false, read_timeout_ns=0, read_header_timeout_ns=0, write_timeout_ns=0, idle_timeout_ns=0, max_header_bytes=1048576, http2_settings=HTTP2Settings(), listenany=false, reuseaddr=true, backlog=128, ) ``` -------------------------------- ### Setting up WebSocket Server in HTTP.jl 2.0 Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/migration-1x.md Use HTTP.WebSockets.listen! to create a WebSocket server that echoes received messages. ```julia server = HTTP.WebSockets.listen!("127.0.0.1", 8080) do ws for msg in ws HTTP.WebSockets.send(ws, msg) end end ``` -------------------------------- ### get Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/client-api.md A convenience function for making HTTP GET requests. It simplifies the process by directly returning the response object, accepting the URL and optional headers, and passing any additional keyword arguments to the underlying `request` function. ```APIDOC ## get ### Description Convenience function for HTTP GET requests. Returns the response object directly. ### Parameters - **url** (`Union{AbstractString, URI}`) - Request URL. - **headers** (`AbstractVector`) - Optional request headers (default: empty). - **client** (`Client`) - Optional client for connection pooling. - **...kwargs** — Additional arguments passed to `request`. ### Example ```julia using HTTP response = HTTP.get("https://httpbin.org/get") println(String(response.body)) # With headers response = HTTP.get("https://api.example.com/data"; headers = ["Authorization" => "Bearer token123"]) ``` ``` -------------------------------- ### Create a Router with Default and Middleware Handlers Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/server.md Initialize an HTTP.Router with default handlers for unmatched routes and apply middleware like a request timeout to all registered routes. ```julia using HTTP timeout = HTTP.Handlers.handlertimeout(5.0; status = 503) router = HTTP.Router( req -> HTTP.Response(404), req -> HTTP.Response(405), timeout, ) ``` -------------------------------- ### Get Trailer Headers Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Retrieves the collection of trailer headers that will be sent after the response body. ```julia trailers(stream::Stream) -> Headers ``` -------------------------------- ### Use BytesBody for Request Payload Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Example of using BytesBody for the payload of an HTTP POST request. ```julia HTTP.request("POST", "http://api.example.com/"; body = "request payload") ``` -------------------------------- ### serve! (Convenience Overloads) Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/server-api.md Convenience functions for setting up stream-oriented servers where handlers process `Stream` objects. These functions simplify the creation of servers focused on incremental data handling. ```APIDOC ## serve! (Convenience Overloads) ### Description Convenience functions for setting up stream-oriented servers where handlers process `Stream` objects. These functions simplify the creation of servers focused on incremental data handling. ### Method Signatures 1. `serve!(handler::Function; network::AbstractString="tcp", address::AbstractString="127.0.0.1:0", stream::Bool=true, kwargs...) -> Server` 2. `serve!(handler::Function, port::Integer; stream::Bool=true, kwargs...) -> Server` 3. `serve!(handler::Function, address::AbstractString, port::Integer; stream::Bool=true, kwargs...) -> Server` ### Parameters - `handler` (Function): The request handler function that operates on streams. - `network` (AbstractString, optional): The network type (default: `"tcp"`). - `address` (AbstractString, optional): The bind address (default: `"127.0.0.1:0"`). - `port` (Integer): The port to listen on. - `stream` (Bool, optional): Indicates if handlers receive `Stream` objects (default: `true`). - `kwargs...`: Additional keyword arguments passed to the `Server` constructor. ### Returns - `Server`: The running server instance. ### Source `src/http_server.jl:1511-1563` ``` -------------------------------- ### Example of Handling CanceledError Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/errors.md Demonstrates how to use HTTP.RequestContext and catch CanceledError when a request is explicitly canceled. ```julia using HTTP import Threads ctx = HTTP.RequestContext() # Cancel the request after 1 second timer = @async begin sleep(1) HTTP.cancel!(ctx; message = "User requested cancel") end try HTTP.request("GET", "https://httpbin.org/delay/10"; context = ctx) catch err if err isa HTTP.CanceledError println("Request canceled: $(err.message)") end end ``` -------------------------------- ### SSE Keep-Alive Ping Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/sse-api.md Illustrates the use of comment lines (starting with ':') for sending keep-alive pings in SSE streams. ```text : keep-alive ``` -------------------------------- ### Configure Proxy Settings in HTTP.jl Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/migration-1x.md Demonstrates various ways to configure proxy settings, including direct, from environment, fixed URL, and SOCKS5 proxies, for HTTP requests. ```julia direct = HTTP.ProxyConfig() from_env = HTTP.ProxyFromEnvironment() fixed = HTTP.ProxyURL("http://proxy.internal:8080"; no_proxy = "localhost,127.0.0.1") socks = HTTP.ProxyURL("socks5h://proxy.internal:1080") HTTP.get(url; proxy = from_env) HTTP.get("http://127.0.0.1:8080"; proxy = direct) ``` -------------------------------- ### Make a GET Request Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/README.md Use `HTTP.get` to fetch data from a URL. The response status and body can be accessed directly. ```julia using HTTP response = HTTP.get("https://api.example.com/users") println(response.status) println(String(response.body)) ``` -------------------------------- ### Use BytesBody for Response Data Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/body-types-api.md Example of setting the body of an HTTP Response with fixed data using BytesBody. ```julia HTTP.Response(200; body = "Hello, World!") ``` -------------------------------- ### HTTP.jl Client Constructor Options Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/configuration.md Lists all available keyword arguments for the HTTP.Client constructor to configure default request behavior and network settings. ```julia client = HTTP.Client(; transport=nothing, check_redirect=nothing, cookiejar=nothing, max_redirects=5, prefer_http2=false, http2_settings=HTTP2Settings(), default_headers=Headers(), default_query=nothing, default_basicauth=nothing, connect_timeout=0.0, request_timeout=0.0, response_header_timeout=0.0, read_idle_timeout=0.0, write_idle_timeout=0.0, local_addr=nothing, ) ``` -------------------------------- ### HTTP.jl 2.0 Request Context Metadata Reading Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/migration-1x.md Read application metadata from the request context using get in 2.0. ```julia request_id = get(HTTP.get_request_context(req), :request_id, nothing) ``` -------------------------------- ### Get Retry Attempts for Response Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/client-api.md Retrieves the number of retries performed before a response was received. This is useful for diagnosing request failures. ```julia retry_attempts(response::Response) -> Int ``` -------------------------------- ### Create Headers with Preallocation Hint Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/headers-api.md Preallocate storage for a specified number of headers to potentially improve performance for collections with a known approximate size. ```julia using HTTP headers = HTTP.Headers(16) # Preallocate for ~16 headers ``` -------------------------------- ### Create and Reuse an HTTP Client Source: https://github.com/juliaweb/http.jl/blob/master/docs/src/guides/client.md Demonstrates creating a reusable HTTP client with custom transport, cookie jar, and retry bucket configurations. The client is used for a request and then closed. ```julia using HTTP server = HTTP.serve!("127.0.0.1", 0; listenany = true) do req payload = req.target == "/stream" ? "streaming response body" : "$(req.method) $(req.target)" return HTTP.Response( 200; headers = ["Content-Type" => "text/plain"], body = payload, ) end base_url = "http://127.0.0.1:$(HTTP.port(server))" retry_bucket = HTTP.RetryBucket(capacity = 100) transport = HTTP.Transport( max_idle_per_host = 2, max_idle_total = 4, proxy = HTTP.ProxyConfig(), ) client = HTTP.Client( transport = transport, cookiejar = HTTP.CookieJar(), retry_bucket = retry_bucket, ) client_response = HTTP.request("GET", base_url * "/reused"; client = client) close(client) HTTP.forceclose(server) (status = client_response.status, body = String(client_response.body)) ``` -------------------------------- ### Configure HTTP Server with Timeouts Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/README.md Set up an HTTP server with specific read, idle, and maximum header byte limits. This is useful for controlling resource usage and preventing denial-of-service attacks. ```julia using HTTP server = HTTP.listen!( "127.0.0.1", 8080; read_timeout_ns = 30 * 1_000_000_000, # 30 seconds idle_timeout_ns = 5 * 60 * 1_000_000_000, # 5 minutes max_header_bytes = 512 * 1024, # 512 KB ) do request HTTP.Response(200; body = "OK") end ``` -------------------------------- ### Load Proxy Settings from Environment Variables Source: https://github.com/juliaweb/http.jl/blob/master/_autodocs/configuration.md Use this snippet to automatically load proxy configurations from standard HTTP proxy environment variables. Ensure the relevant environment variables (HTTP_PROXY, HTTPS_PROXY, NO_PROXY) are set before creating the client. ```julia using HTTP # Use proxy settings from environment client = HTTP.Client(; proxy = HTTP.ProxyFromEnvironment()) # All requests go through the configured proxy response = HTTP.get(client, "https://example.com") ```