#include "mongoose.h" // struct mg_mgr mg_manager; // http- struct mg_connection *http_mg_conn; // http- struct mg_serve_http_opts s_http_server_opts; const char *example_data_buf = "{ \"some_response_data\": \"Hello world!\" }"; const char *html_error_template = "<html>\n" "<head><title>%d %s</title></head>\n" "<body bgcolor=\"white\">\n" "<center><h1>%d %s</h1></center>\n" "</body>\n" "</html>\n"; //----------------------------------------------------------------------------- // void http_request_handler(struct mg_connection *conn, int ev, void *ev_data) { switch (ev) { case MG_EV_ACCEPT: { // - conn->sock break; } case MG_EV_HTTP_REQUEST: { struct http_message *http_msg = (struct http_message *)ev_data; // HTTP- // http_msg->uri - URI // http_msg->body - // if (mg_vcmp(&http_msg->uri, "/api/v1.0/queue/get") == 0) { mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Server: MyWebServer\r\n" "Content-Type: application/json\r\n" "Content-Length: %d\r\n" "Connection: close\r\n" "\r\n", (int)strlen(example_data_buf)); mg_send(conn, example_data_buf, strlen(example_data_buf)); // conn->flags // , : conn->flags |= MG_F_SEND_AND_CLOSE; } // 404 else if (strncmp(http_msg->uri.p, "/api", 4) == 0) { char buf_404[2048]; sprintf(buf_404, html_error_template, 404, "Not Found", 404, "Not Found"); mg_printf(conn, "HTTP/1.1 404 Not Found\r\n" "Server: MyWebServer\r\n" "Content-Type: text/html\r\n" "Content-Length: %d\r\n" "Connection: close\r\n" "\r\n", (int)strlen(buf_404)); mg_send(conn, buf_404, strlen(buf_404)); conn->flags |= MG_F_SEND_AND_CLOSE; } // URI - else mg_serve_http(conn, http_msg, s_http_server_opts); break; } case MG_EV_RECV: { // *(int *)ev_data break; } case MG_EV_SEND: { // *(int *)ev_data break; } case MG_EV_CLOSE: { // break; } default: { break; } } } bool flag_kill = false; //----------------------------------------------------------------------------- void termination_handler(int) { flag_kill = true; } //--------------------------------------------------------------------------- int main(int, char *[]) { signal(SIGTERM, termination_handler); signal(SIGSTOP, termination_handler); signal(SIGKILL, termination_handler); signal(SIGINT, termination_handler); signal(SIGQUIT, termination_handler); // s_http_server_opts.document_root = "/var/www"; // s_http_server_opts.enable_directory_listing = "no"; // mg_mgr_init(&mg_manager, NULL); // localhost:8080 - http_request_handler http_mg_conn = mg_bind(&mg_manager, "127.0.0.1:8080", http_request_handler); if (!http_mg_conn) return -1; // http mg_set_protocol_http_websocket(http_mg_conn); while (!flag_kill) { // - // mg_connection->sock // ( ) select/poll, // sleep- // ... // int ms_wait = 1000; // ms_wait // bool has_other_work_to_do = false; // mg_mgr_poll(&mg_manager, has_other_work_to_do ? 0 : ms_wait); } // mg_mgr_free(&mg_manager); return 0; }
location /api { proxy_pass http://127.0.0.1:8080; }
Source: https://habr.com/ru/post/321430/
All Articles