mongoose/examples/http-restful-server/main.c

56 lines
2.3 KiB
C
Raw Normal View History

2020-12-10 21:26:05 +08:00
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
2020-12-18 17:08:28 +08:00
// HTTP server example. This server serves both static and dynamic content.
2021-07-13 21:40:52 +08:00
// It opens two ports: plain HTTP on port 8000 and HTTP on port 8443.
2020-12-18 17:08:28 +08:00
// It implements the following endpoints:
// /api/f1 - respond with JSON string {"result": 123}
// /api/f2/:id - wildcard example, respond with JSON string {"result": "URI"}
2021-07-13 21:40:52 +08:00
// any other URI serves static files from s_root_dir
2020-12-18 17:08:28 +08:00
//
// To enable SSL/TLS (using self-signed certificates in PEM files),
2021-07-13 21:40:52 +08:00
// 1. make MBEDTLS_DIR=/path/to/your/mbedtls/installation
// 2. curl -k https://127.0.0.1:8443
2020-12-10 21:26:05 +08:00
#include "mongoose.h"
2021-07-13 21:40:52 +08:00
static const char *s_http_addr = "http://0.0.0.0:8000"; // HTTP port
static const char *s_https_addr = "https://0.0.0.0:8443"; // HTTPS port
static const char *s_root_dir = ".";
2020-12-10 21:26:05 +08:00
2021-07-13 21:40:52 +08:00
// We use the same event handler function for HTTP and HTTPS connections
// fn_data is NULL for plain HTTP, and non-NULL for HTTPS
2020-12-10 21:26:05 +08:00
static void fn(struct mg_connection *c, int ev, void *ev_data, void *fn_data) {
2021-07-13 21:40:52 +08:00
if (ev == MG_EV_ACCEPT && fn_data != NULL) {
struct mg_tls_opts opts = {
//.ca = "ca.pem", // Uncomment to enable two-way SSL
.cert = "server.pem", // Certificate PEM file
2021-08-02 07:23:01 +08:00
.certkey = "server.pem", // This pem contains both cert and key
};
mg_tls_init(c, &opts);
} else if (ev == MG_EV_HTTP_MSG) {
2020-12-10 21:26:05 +08:00
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
if (mg_http_match_uri(hm, "/api/f1")) {
2020-12-18 06:45:22 +08:00
mg_http_reply(c, 200, "", "{\"result\": %d}\n", 123); // Serve REST
2020-12-10 21:26:05 +08:00
} else if (mg_http_match_uri(hm, "/api/f2/*")) {
2020-12-18 06:45:22 +08:00
mg_http_reply(c, 200, "", "{\"result\": \"%.*s\"}\n", (int) hm->uri.len,
2020-12-10 21:26:05 +08:00
hm->uri.ptr);
} else {
2021-07-13 21:40:52 +08:00
struct mg_http_serve_opts opts = {.root_dir = s_root_dir};
mg_http_serve_dir(c, ev_data, &opts);
2020-12-10 21:26:05 +08:00
}
}
(void) fn_data;
}
int main(void) {
struct mg_mgr mgr; // Event manager
mg_log_set("2"); // Set to 3 to enable debug
2020-12-10 21:26:05 +08:00
mg_mgr_init(&mgr); // Initialise event manager
2021-07-13 21:40:52 +08:00
mg_http_listen(&mgr, s_http_addr, fn, NULL); // Create HTTP listener
mg_http_listen(&mgr, s_https_addr, fn, (void *) 1); // HTTPS listener
for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop
2020-12-10 21:26:05 +08:00
mg_mgr_free(&mgr);
return 0;
}