aisl/examples/hello-world.c

109 lines
2.3 KiB
C

/******************************************************************************
*
* 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 */
struct aisl_config config = AISL_CONFIG_DEFAULT;
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(&config)) != NULL )
{
if (aisl_listen( aisl, "0.0.0.0", port ) != NULL)
{
/* Set up request callback */
aisl_set_callback( aisl
, AISL_EVENT_STREAM_REQUEST
, AISL_CALLBACK(hello_world) );
/* launch application loop */
fprintf(stdout, "Entering main loop" );
for(;;)
{
status = aisl_run_cycle(aisl);
if ( status != AISL_SUCCESS )
aisl_sleep(aisl, 500);
}
aisl_free(aisl);
}
else
fprintf(stderr, "Failed to initialize HTTP server" );
}
else
fprintf(stderr, "Failed to initialize AISL");
(void)argc;
(void)argv;
return 0;
}