ESP-IDF webserver:如何用 JSON 成功或错误消息响应

这些实用函数允许你轻松地用 {"status": "ok"}{"status": "error", "error": "..."} 响应。

注意错误消息不会被转义而是按原样发送,因此某些包含引号(")或其他特殊字符的错误消息可能会破坏 JSON。

http_response_helpers.cpp
esp_err_t SendStatusOK(httpd_req_t *request) {
    httpd_resp_set_type(request, "application/json");
    httpd_resp_sendstr(request, "{\"status\":\"ok\"}");
    return ESP_OK;
}

esp_err_t SendStatusError(httpd_req_t *request, const char* description) {
    httpd_resp_set_type(request, "application/json");
    httpd_resp_send_chunk(request, "{\"status\":\"error\", \"error\": \"", HTTPD_RESP_USE_STRLEN);
    // NOTE: We silently assume that description does not have any special characters
    httpd_resp_send_chunk(request, description, HTTPD_RESP_USE_STRLEN);
    httpd_resp_send_chunk(request, "\"}", HTTPD_RESP_USE_STRLEN);
    httpd_resp_send_chunk(request, nullptr, 0); // Finished
    return ESP_OK;
}

Check out similar posts by category: C/C++, ESP8266/ESP32