/* * Copyright (c) 2023 Fancy Code. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FxHttpServer.h" #include "ILog.h" #include "httpserver.h" #include extern int gHttpServerRuning; static struct http_server_s *server = NULL; static struct http_server_s *poll_server = NULL; static HttpHandleCallback gHttpHandle = NULL; static void response_handle(const char *responseStr, void *context) { struct http_response_s *response = (struct http_response_s *)context; if (NULL != responseStr) { http_response_header(response, "Content-Type", "text/plain"); http_response_body(response, responseStr, strlen(responseStr)); } } static void handle_request(struct http_request_s *request) { http_request_connection(request, HTTP_AUTOMATIC); struct http_response_s *response = http_response_init(); http_response_status(response, 200); http_string_t url = http_request_target(request); gHttpHandle(url.buf, url.len, response_handle, response); http_respond(request, response); } StatusCode FxHttpServerInit(HttpHandleCallback httpHandle, const int port) { // poll_server = http_server_init(port + 1, handle_request); if (NULL == httpHandle) { LogError("FxHttpServerInit failed. Callback function is nullptr.\n"); return CreateStatusCode(STATUS_CODE_NOT_OK); } server = http_server_init(port, handle_request); if (!server) { LogError("http_server_init failed.\n"); return CreateStatusCode(STATUS_CODE_NOT_OK); } gHttpHandle = httpHandle; // http_server_listen_poll(poll_server); http_server_listen(server); return CreateStatusCode(STATUS_CODE_OK); } StatusCode FxHttpServerExit(void) { gHttpServerRuning = 0; return CreateStatusCode(STATUS_CODE_OK); } StatusCode FxHttpServerUnInit(void) { free(server); server = NULL; free(poll_server); poll_server = NULL; return CreateStatusCode(STATUS_CODE_OK); }