Dummy Forwarding Server

30 Views Asked by At

I need to create an ESP32 program that creates a dummy server with the ES32 responding to HTTP requests from a client by sending the exact same query to a server and then forwarding the packet forward to the original client without any change.

The issue is that the responses from the client are quite large (on the orders of 12kb) and need to be forwarded rapidly with minimal latency or lag.

So far this is the ESP32 handler that I have written for the task but I am wondering if there is a faster way of doing so that's less error prone as this method seems to be incapable of working at the speed I wish for it do.

static esp_err_t root_get_handler(httpd_req_t *req)
{
    static char buf[18000] = {0};
    size_t buf_len = sizeof(buf);
    char param_value[5];
    int content_length = 0;

    // Get the value of the 'param' query parameter
    if (httpd_query_key_value(req->uri, "param", param_value, sizeof(param_value)) == ESP_OK) {
        ESP_LOGI(TAG, "Received param value: %s", param_value);

        // Create an HTTP client to send a request to the destination server
        esp_http_client_config_t config = {
            .url = "http://192.168.97.37:8080",
        };
        esp_http_client_handle_t client = esp_http_client_init(&config);
        esp_http_client_set_method(client, HTTP_METHOD_GET);

        // Add the 'param' query parameter to the request
        char dest_url[100];
        snprintf(dest_url, sizeof(dest_url), "%s?param=%s", "http://192.168.97.37:8080", param_value);
        esp_http_client_set_url(client, dest_url);
        esp_err_t err = esp_http_client_perform(client);
        if (err != ESP_OK) {
            ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
            // Get the response from the destination server
        } else {
            content_length = esp_http_client_fetch_headers(client);
            if (content_length < 0) {
                ESP_LOGE(TAG, "HTTP client fetch headers failed");
            } 
            else {
                int data_read = esp_http_client_read_response(client, buf, MAX_HTTP_OUTPUT_BUFFER);
                if (data_read >= 0) {
                    ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %"PRId64,
                    esp_http_client_get_status_code(client),
                    esp_http_client_get_content_length(client));
                    ESP_LOG_BUFFER_HEX(TAG, buf, data_read);
                } 
                else {
                    ESP_LOGE(TAG, "Failed to read response");
                }
            }
        }

        // Cleanup
        esp_http_client_cleanup(client);
    }
    else {
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing 'param' query parameter");
    }

    return ESP_OK;
}
0

There are 0 best solutions below