2022-07-12 03:11:15 +08:00
|
|
|
// Copyright (c) 2022 Cesanta Software Limited
|
|
|
|
// All rights reserved
|
|
|
|
//
|
|
|
|
// REST basics example
|
|
|
|
// It implements the following endpoints:
|
|
|
|
// /api/f1 - respond with a simple mock result
|
|
|
|
// /api/sum - respond with the result of adding two numbers
|
|
|
|
// any other URI serves static files from s_root_dir
|
|
|
|
// Results are JSON strings
|
|
|
|
|
|
|
|
#include "mongoose.h"
|
|
|
|
|
|
|
|
static const char *s_http_addr = "http://localhost:8000"; // HTTP port
|
|
|
|
static const char *s_root_dir = "web_root";
|
|
|
|
|
2024-01-09 04:34:34 +08:00
|
|
|
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
2022-07-12 03:11:15 +08:00
|
|
|
if (ev == MG_EV_HTTP_MSG) {
|
|
|
|
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
2024-04-18 03:13:10 +08:00
|
|
|
if (mg_match(hm->uri, mg_str("/api/f1"), NULL)) {
|
2023-04-14 21:11:12 +08:00
|
|
|
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "{%m:%d}\n",
|
2023-05-18 01:26:45 +08:00
|
|
|
MG_ESC("result"), 123);
|
2024-04-18 03:13:10 +08:00
|
|
|
} else if (mg_match(hm->uri, mg_str("/api/sum"), NULL)) {
|
2022-07-12 03:11:15 +08:00
|
|
|
// Attempt to fetch a JSON array from the body, hm->body
|
|
|
|
struct mg_str json = hm->body;
|
|
|
|
double num1, num2;
|
|
|
|
if (mg_json_get_num(json, "$[0]", &num1) &&
|
|
|
|
mg_json_get_num(json, "$[1]", &num2)) {
|
|
|
|
// Success! create a JSON response
|
2023-04-14 21:11:12 +08:00
|
|
|
mg_http_reply(c, 200, "Content-Type: application/json\r\n", "{%m:%g}\n",
|
2023-05-18 01:26:45 +08:00
|
|
|
MG_ESC("result"), num1 + num2);
|
2022-07-12 03:11:15 +08:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
struct mg_http_serve_opts opts = {.root_dir = s_root_dir};
|
2023-12-24 06:02:05 +08:00
|
|
|
mg_http_serve_dir(c, hm, &opts);
|
2022-07-12 03:11:15 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(void) {
|
|
|
|
struct mg_mgr mgr; // Event manager
|
2022-08-01 18:19:32 +08:00
|
|
|
mg_log_set(MG_LL_DEBUG); // Set log level
|
2022-07-12 03:11:15 +08:00
|
|
|
mg_mgr_init(&mgr); // Initialise event manager
|
|
|
|
mg_http_listen(&mgr, s_http_addr, fn, NULL); // Create HTTP listener
|
|
|
|
for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop
|
|
|
|
mg_mgr_free(&mgr);
|
|
|
|
return 0;
|
|
|
|
}
|