Bu yazı, LittleFS’te saklanan dosyaların JSON listesini döndüren bir GET endpoint’ini ESP32’ye (ESP-IDF esp_http_server) nasıl uygulayacağını ve curl ile nasıl sorgulayacağını gösteriyor.
Endpoint
example.txt
GET /api/files (kök dizini listeler)
GET /api/files?path=dir (bir alt dizini listeler)Yanıt:
response.json
{"files":[
{"path":"index.html","size":81696},
{"path":"app.js","size":1920}
]}Firmware handler’ı (ESP-IDF)
HTTPHandlersFiles.cpp
esp_err_t handleListFiles(httpd_req_t *req) {
QueryURLParser parser(req);
std::string dir = "/";
if (parser.HasParameter("path")) {
dir = parser.GetParameter("path");
}
std::string rel;
if (!sanitize_path(dir, rel)) {
httpd_resp_set_status(req, "400 Bad Request");
httpd_resp_sendstr(req, "{\"error\": \"Invalid path\"}");
return ESP_OK;
}
cJSON *root = cJSON_CreateObject();
cJSON *arr = cJSON_CreateArray();
const auto files = list_files_for_api(std::string(LittleFSManager::mountPoint()), rel);
for (const auto& f : files) {
cJSON *obj = cJSON_CreateObject();
cJSON_AddStringToObject(obj, "path", f.path.c_str());
cJSON_AddNumberToObject(obj, "size", (double)f.size);
cJSON_AddItemToArray(arr, obj);
}
cJSON_AddItemToObject(root, "files", arr);
char *json_str = cJSON_PrintUnformatted(root);
set_content_type_with_charset(req, "application/json");
httpd_resp_send(req, json_str, strlen(json_str));
free(json_str);
cJSON_Delete(root);
return ESP_OK;
}Yinelemeli listeleme yardımcısı, ESP-IDF VFS katmanı üzerinden LittleFS’te çalışan düz POSIX çağrıları (opendir/readdir/stat) kullanır:
HTTPHandlersFiles.cpp
std::vector<ListedFile> list_files_for_api(const std::string& base, const std::string& relpath) {
std::vector<ListedFile> out;
// ... base + "/" + relpath'i opendir()/readdir() ile yinelemeli gez,
// her normal dosya için {relative_path, st_size} ekle
// ve nodes.json gibi korunan sistem dosyalarını atla
return out;
}Handler’ı kaydet (sondaki-eğik-çizgi varyantı, / ekleyen istemcilerin 404 almasını önler):
HTTPServerWrapper.cpp
static const httpd_uri_t listFilesHandler = {
.uri = "/api/files",
.method = HTTP_GET,
.handler = handleListFiles,
.user_ctx = NULL
};
static const httpd_uri_t listFilesHandlerSlash = {
.uri = "/api/files/",
.method = HTTP_GET,
.handler = handleListFiles,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &listFilesHandler);
httpd_register_uri_handler(server, &listFilesHandlerSlash);curl ile sorgula
list.sh
curl -s "http://10.56.11.162/api/files" | jqoutput.json
{
"files": [
{"path": "can_monitor.html", "size": 16692},
{"path": "index.html", "size": 81696},
{"path": "logging.html", "size": 4799}
]
}İlgili yazılar
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow