vibe.d beta banner
get vibe.d
0.7.30

Function registerWebInterface

Registers a HTTP/web interface based on a class instance.

Each public method of the given class instance will be mapped to a HTTP route. Property methods are mapped to GET/PUT and all other methods are mapped according to their prefix verb. If the method has no known prefix, POST is used. The rest of the name is mapped to the path of the route according to the given method_style. Note that the prefix word must be all-lowercase and is delimited by either an upper case character, a non-alphabetic character, or the end of the string.

The following table lists the mappings from prefix verb to HTTP verb:

HTTP method Recognized prefixes
GET get, query
PUT set, put
POST add, create, post
DELETE remove, erase, delete
PATCH update, patch

Method parameters will be sourced from either the query string or form data of the request, or, if the parameter name has an underscore prefixed, from the vibe.http.server.HTTPServerRequest.params map.

The latter can be used to inject custom data in various ways. Examples of this are placeholders specified in a @path annotation, values computed by a @before annotation, error information generated by the @errorDisplay annotation, or data injected manually in a HTTP method handler that processed the request prior to passing it to the generated web interface handler routes.

Methods that return a class or interface instance, instead of being mapped to a single HTTP route, will be mapped recursively by iterating the public routes of the returned instance. This way, complex path hierarchies can be mapped to class hierarchies.

Prototype

URLRouter registerWebInterface(C, vibe.web.common.MethodStyle method_style)(
  URLRouter router,
  C instance,
  WebInterfaceSettings settings = null
);

Parameter conversion rules

For mapping method parameters without a prefixed underscore to query/form fields, the following rules are applied:

  • An array of values is mapped to <parameter_name>_<index>, where index denotes the zero based index of the array entry. The length of the array is determined by searching for the first non-existent index in the set of form fields.
  • Nullable!T typed parameters, as well as parameters with default values, are optional parameters and are allowed to be missing in the set of form fields. All other parameter types require the corresponding field to be present and will result in a runtime error otherwise.
  • struct type parameters that don't define a fromString or a fromStringValidate method will be mapped to one form field per struct member with a scheme similar to how arrays are treated: <parameter_name>_<member_name>
  • Boolean parameters will be set to true if a form field of the corresponding name is present and to false otherwise. This is compatible to how check boxes in HTML forms work.
  • All other types of parameters will be converted from a string by using the first available means of the following: a static fromStringValidate method, a static fromString method, using std.conv.to!T.
  • Any of these rules can be applied recursively, so that it is possible to nest arrays and structs appropriately.

Special parameters

Supported attributes

The following attributes are supported for annotating methods of the registered class:

@before, @after, @errorDisplay, @vibe.web.common.method, @vibe.web.common.path, @vibe.web.common.contentType

The @path attribute can also be applied to the class itself, in which case it will be used as an additional prefix to the one in WebInterfaceSettings.urlPrefix.

Parameters

NameDescription
router The HTTP router to register to
instance Class instance to use for the web interface mapping
settings Optional parameter to customize the mapping process

Example

Gives an overview of the basic features. For more advanced use, see the example in the "examples/web/" directory.

import vibe.http.router;
import vibe.http.server;
import vibe.web.web;

class WebService {
	private {
		SessionVar!(string, "login_user") m_loginUser;
	}

	@path("/")
	void getIndex(string _error = null)
	{
		//render!("index.dt", _error);
	}

	// automatically mapped to: POST /login
	@errorDisplay!getIndex
	void postLogin(string username, string password)
	{
		enforceHTTP(username.length > 0, HTTPStatus.forbidden,
			"User name must not be empty.");
		enforceHTTP(password == "secret", HTTPStatus.forbidden,
			"Invalid password.");
		m_loginUser = username;
		redirect("/profile");
	}

	// automatically mapped to: POST /logout
	void postLogout()
	{
		terminateSession();
		redirect("/");
	}

	// automatically mapped to: GET /profile
	void getProfile()
	{
		enforceHTTP(m_loginUser.length > 0, HTTPStatus.forbidden,
			"Must be logged in to access the profile.");
		//render!("profile.dt")
	}
}

void run()
{
	auto router = new URLRouter;
	router.registerWebInterface(new WebService);

	auto settings = new HTTPServerSettings;
	settings.port = 8080;
	listenHTTP(settings, router);
}
Authors

Sönke Ludwig

Copyright

© 2013-2016 RejectedSoftware e.K.

License

Subject to the terms of the MIT license, as written in the included LICENSE.txt file.