74 lines
1.8 KiB
C
74 lines
1.8 KiB
C
#include <stdio.h>
|
|
#include "esp_err.h"
|
|
#include "esp_log.h"
|
|
#include "esp_http_server.h"
|
|
#include "HTTPServe.h"
|
|
|
|
esp_err_t start_server(HTTP_serve_config_t config){
|
|
httpd_config_t serv_config = HTTPD_DEFAULT_CONFIG();
|
|
serv_config.uri_match_fn = httpd_uri_match_wildcard;
|
|
httpd_handle_t server = NULL;
|
|
|
|
ESP_LOGI("SERV", "addr %i", (&config)->mountpoint);
|
|
|
|
httpd_uri_t uri_get = {
|
|
.uri = config.getUri,
|
|
.method = HTTP_GET,
|
|
.handler = get_handler,
|
|
.user_ctx = &config,
|
|
};
|
|
httpd_uri_t uri_post = {
|
|
.uri = config.postUri,
|
|
.method = HTTP_POST,
|
|
.handler = post_handler,
|
|
.user_ctx = NULL,
|
|
};
|
|
|
|
esp_err_t status = httpd_start(&server, &serv_config);
|
|
if(status == ESP_OK) {
|
|
httpd_register_uri_handler(server, &uri_get);
|
|
httpd_register_uri_handler(server, &uri_post);
|
|
}
|
|
|
|
return status;
|
|
}
|
|
|
|
esp_err_t get_handler(httpd_req_t *req){
|
|
char* prefix = ((HTTP_serve_config_t*)req->user_ctx)->mountpoint;
|
|
const char* uri = req->uri;
|
|
bool inRoot = !strcmp(uri,"/");
|
|
char filename[strlen(uri) + strlen(prefix) + 1 + (inRoot?10:0)];
|
|
strcpy(filename, prefix);
|
|
strcat(filename, uri);
|
|
if(inRoot)
|
|
strcat(filename, "index.html");
|
|
const char err404[] = "404 page not found";
|
|
|
|
ESP_LOGI("HTTP","req : %s %s", prefix, filename);
|
|
FILE* f;
|
|
if(!(f = fopen(filename,"r"))){
|
|
httpd_resp_send(req, err404, HTTPD_RESP_USE_STRLEN);
|
|
return ESP_FAIL;
|
|
}
|
|
|
|
if(strstr(uri, ".js") != NULL)
|
|
httpd_resp_set_type(req, "application/javascript");
|
|
char chunk[1024];
|
|
size_t chunksize;
|
|
do {
|
|
chunksize = fread(chunk, 1, sizeof(chunk), f);
|
|
if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK) {
|
|
fclose(f);
|
|
return ESP_FAIL;
|
|
}
|
|
} while (chunksize != 0);
|
|
|
|
httpd_resp_send_chunk(req, NULL, 0);
|
|
fclose(f);
|
|
return ESP_OK;
|
|
}
|
|
|
|
esp_err_t post_handler(httpd_req_t *req){
|
|
return ESP_OK;
|
|
}
|