-
Notifications
You must be signed in to change notification settings - Fork 1
Web Server API
This example is in examples/webserver
user.m
function user() %#codegen
webserver(8080, 'myserver'); % start webserver on port 8080
sleep(60); % hang around for a minute, then shutdownfunction myserver() % called on every page request
switch (webserver.url())
case '/'
webserver.html('hello world');
case '/bob'
stllog('in /bob');
webserver.html('<html><body>hello <b>from</b> /bob</body></html>');
a = webserver.getarg('a');
if ~isempty(a)
stllog('a = %s', cstring(a));
end
case '/alice'
vals.a = 1;
vals.b = 2;
webserver.template('templates/alice.html', vals);
case '/duck':
webserver.file('duck.jpg', 'image/jpeg');The switch statement handles the particular URLs that are supported by the tiny webserver:
-
/sends simple text to the web browser. -
/bobsends an HTML formatted string to the web browser and also demonstrates access to GET arguments (the things after the question mark on the end of a URL). -
/alicesends the contents of the template filetemplates/alice.htmland does the substitutions defined by the structvals. The template variableais replaced with1and so on. The numeric values are converted to strings usingnum2strwhich will convert a row-vector to a space separated sequence of numbers. -
/duckreturn the contents of the data file with the content typeimage/jpegwhich will be rendered in the web browser.
If the URL is not amongst the cases, or if no content is generated by a call to a webserver method a 404 error will be generated.
If the server is running on the same machine as the web browser, we can access it at localhost.
The page bob has the URL localhost:8080/bob and demonstrates how GET arguments can be accessed.
A request to the URL localhost:8080/bob generates the following log:
2018-09-05 08:49:41.514573 [WEB] web: GET request for URL /bob using HTTP/1.1
2018-09-05 08:49:41.514599 [WEB] in /bob
A request to the URL localhost:8080/bob?a=56 generates the following log:
2018-09-05 08:49:46.763896 [WEB] web: GET request for URL /bob using HTTP/1.1
2018-09-05 08:49:46.763931 [WEB] in /bob
2018-09-05 08:49:46.763936 [WEB] a = 56
A request to the URL localhost:8080/bob?a=hello generates the following log:
2018-09-05 08:49:54.570648 [WEB] web: GET request for URL /bob using HTTP/1.1
2018-09-05 08:49:54.570674 [WEB] in /bob
2018-09-05 08:49:54.570679 [WEB] a = hello
Note that the GET arguments are always strings. You can convert to numerical form using str2num which will return [] is the string is non-numeric.
A request to the URL localhost:8080/alice processes the HTML template file
<html>
<body>
<p>This is a test page</p>
<p>a = <TMPL_VAR name="a"></p>
<p>b = <TMPL_VAR name="b"></p>
</body>
</html>substituting (the TMPL_VAR tags) the values from the passed structure
and generating this web page:

A request to the URL localhost:8080/duck shows an image of a duck, uploaded as image/jpeg content from the local file duck.jpg.