aisl/examples/hello-world.c

116 lines
2.5 KiB
C
Raw Normal View History

2019-03-18 09:13:02 +01:00
/******************************************************************************
*
* Copyright (c) 2017-2019 by Löwenware Ltd
* Please, refer LICENSE file for legal information
*
******************************************************************************/
/**
* @file hello-world.c
* @author Ilja Kartašov <ik@lowenware.com>
* @brief AISL usage example: Hello World
*
* @see https://lowenware.com/aisl/
*/
#include <stdio.h>
#include <stdlib.h>
/* Include library meta header */
#include <aisl/aisl.h>
#define DEFAULT_HTTP_PORT 8080 /**< Default HTTP server port */
static bool
hello_world(aisl_stream_t s)
{
aisl_status_t status;
const char html[] =
"<html>"
"<head>"
"<title>Hello World</title>"
"</head>"
"<body>"
"<h1>Hello World</h1>"
"<p>Powered by AISL</p>"
"</body>"
"</html>";
status = aisl_response(s, AISL_HTTP_OK, sizeof(html)-1);
if (status == AISL_SUCCESS)
{
if (aisl_write(s, html, sizeof(html)-1) != -1)
{
aisl_flush(s);
}
else
aisl_reject(s);
}
return true; /**< do not propagate event anymore */
}
int
main(int argc, char ** argv)
{
aisl_t aisl; /**< AISL instance pointer */
aisl_status_t status; /**< AISL status code */
uint16_t port = 0;
/* Try to use first argument as a port number */
if (argc > 1)
port = strtoll(argv[1], NULL, 10);
/* Fallback to default if not set or failed */
if (port == 0)
port = DEFAULT_HTTP_PORT;
/* Initialize instance */
if ( (aisl = aisl_new(NULL)) != NULL )
{
if (aisl_listen( aisl, "0.0.0.0", port ) != NULL)
{
aisl_callback_t callback = AISL_CALLBACK(hello_world);
/* Set up request callback */
status = aisl_set_callback( aisl
, NULL
, AISL_EVENT_STREAM_REQUEST
, callback );
/* if callback was set, launch application loop */
if ( status == AISL_SUCCESS )
{
fprintf(stdout, "Entering main loop" );
for(;;)
{
status = aisl_run_cycle(aisl);
if ( status != AISL_SUCCESS )
aisl_sleep(aisl, 500);
}
}
else
fprintf(stderr, "Failed to register callback" );
aisl_free(aisl);
}
else
fprintf(stderr, "Failed to initialize HTTP server" );
}
else
fprintf(stderr, "Failed to initialize AISL");
(void)argc;
(void)argv;
return 0;
}