Skip to content

ddn.api.net.http.client

Small, robust, and idiomatic HTTP client API.

This module defines:

  • HttpClient for synchronous request/response usage
  • AsyncHttpClient for asynchronous request/response usage (via HttpFuture!HttpResponse)

It is intended to be implemented by concrete backends (for example, a libcurl-based implementation).

Module Declaration

module ddn.api.net.http.client;

Classes

HttpException

class HttpException : Exception

Base exception type for the HTTP client API.

Constructor:

this(string msg, Throwable next = null);
Parameter Description
msg Human readable error message
next Optional chained exception

HttpTimeoutException

class HttpTimeoutException : HttpException

Exception thrown when an HTTP operation times out.

Constructor:

this(string msg, Throwable next = null);
Parameter Description
msg Human readable error message
next Optional chained exception

Enums

HttpMethod

enum HttpMethod

Standard HTTP methods.

Member Description
GET GET method
HEAD HEAD method
POST POST method
PUT PUT method
DELETE DELETE method
OPTIONS OPTIONS method
TRACE TRACE method
CONNECT CONNECT method
PATCH PATCH method

Structs

HttpHeaders

struct HttpHeaders

A case-insensitive header map.

Header names are normalized to lower case for lookups.

In addition to the explicit set/has/get/remove methods, HttpHeaders also supports map-like usage:

HttpHeaders h;
h["Content-Type"] = "text/plain"; // set
auto ct = h["content-type"];      // get ("" if missing)

if (auto p = "content-type" in h) {
   // `p` is a pointer to the stored value
   assert(*p == "text/plain");
}

h["content-type"] = null; // remove

foreach (k, v; h) {
   // iterate normalized keys and values
}

Methods

set
void set(string name, string value);

Sets (adds or replaces) a header.

Parameter Description
name Header name
value Header value

has
bool has(string name) const;

Returns true if the header is present.

Parameter Description
name Header name

get
string get(string name, string defaultValue = "") const;

Gets a header value.

Parameter Description
name Header name
defaultValue Value returned when the header is absent

Returns: The stored header value, or defaultValue if missing.


remove
void remove(string name);

Removes a header if present.

Parameter Description
name Header name

length
@property size_t length() const;

Returns the number of stored headers.


values
@property const(string[string]) values() const;

Returns the underlying normalized header map.


HttpRequest

struct HttpRequest

An HTTP request.

Fields

Field Type Description
method HttpMethod Request method
url string Absolute URL
headers HttpHeaders Request headers
body ubyte[] Request body bytes
operationTimeout core.time.Duration Total operation timeout; 0.seconds means "use client default"
connectTimeout core.time.Duration Connection timeout; 0.seconds means "use client default"
maxRedirects uint Redirect limit; uint.max means "use client default"

Constructor

this(HttpMethod method, string url);

Constructs a request with the given method and URL.

Parameter Description
method Request method
url Absolute URL

Example:

import ddn.api.net.http.client;

auto req = HttpRequest(HttpMethod.GET, "https://example.com/")
   .withHeader("Accept", "application/json");

Methods

withHeader
HttpRequest withHeader(string name, string value) const;

Returns a copy of this request with an additional/replaced header.

Parameter Description
name Header name
value Header value

withBody
HttpRequest withBody(const(ubyte)[] data) const;

Returns a copy of this request with a body.

Parameter Description
data Body bytes

withOperationTimeout
HttpRequest withOperationTimeout(core.time.Duration d) const;

Returns a copy of this request with an operation timeout.

Parameter Description
d Total operation timeout (non-negative)

withConnectTimeout
HttpRequest withConnectTimeout(core.time.Duration d) const;

Returns a copy of this request with a connect timeout.

Parameter Description
d Connection timeout (non-negative)

withMaxRedirects
HttpRequest withMaxRedirects(uint max) const;

Returns a copy of this request with a redirect limit.

Passing uint.max means "use client default".

Parameter Description
max Maximum number of redirects

HttpResponse

struct HttpResponse

An HTTP response.

Fields

Field Type Description
statusCode ushort HTTP status code
reasonPhrase string HTTP reason phrase (may be empty)
headers HttpHeaders Response headers
body ubyte[] Response body bytes

Methods

isSuccess
bool isSuccess() const;

Returns true if statusCode is in the 2xx range.


bodyAsString
string bodyAsString() const;

Returns the body as a string.

This method assumes the body is valid UTF-8 and performs no decoding.


string header(string name, string defaultValue = "") const;

Convenience accessor for a header on the response.

Parameter Description
name Header name
defaultValue Value returned when the header is absent

HttpFuture(T)

struct HttpFuture(T)

A future representing an asynchronously produced value.

HttpFuture is created by a corresponding HttpPromise and can be used to wait for completion and retrieve the resulting value.

Methods

isValid
@property bool isValid() const;

Returns true if this future refers to a valid asynchronous result.


ready
bool ready();

Returns true if the future is already completed.


wait
void wait();

Blocks until the future is completed.


get
T get();

Blocks until completion, then returns the value or throws the stored error.


HttpPromise(T)

struct HttpPromise(T)

A promise that can be completed with a value or an error.

HttpPromise is used by asynchronous client implementations to complete the corresponding HttpFuture.

Methods

make
static HttpPromise!T make();

Creates a new promise.


future
HttpFuture!T future();

Returns the future associated with this promise.


succeed
void succeed(T value);

Completes the promise successfully.

Parameter Description
value Produced value

fail
void fail(Throwable error);

Completes the promise with an error.

Parameter Description
error Error to store and rethrow on HttpFuture.get()

Interfaces

HttpClient

interface HttpClient

Synchronous HTTP client interface.

Methods

request
HttpResponse request(ref const HttpRequest request);

Performs an HTTP request and returns the full response.

Parameter Description
request Request description

close
void close();

Releases any resources associated with the client.


AsyncHttpClient

interface AsyncHttpClient

Asynchronous HTTP client interface.

Methods

requestAsync
HttpFuture!HttpResponse requestAsync(ref const HttpRequest request);

Starts an HTTP request and returns a future for its response.

Parameter Description
request Request description

close
void close();

Releases any resources associated with the client.


See Also

  • ddn.net.http.client.curl — a libcurl-based synchronous HttpClient implementation (subpackage)
  • demo/net/http_client_vibed.d — example async usage with vibe.d (single-file demo)
  • demo/net/http_client_curl.d — example synchronous usage with libcurl (single-file demo)