Skip to content

Instantly share code, notes, and snippets.

@fabiovila
Last active January 8, 2018 23:29
Show Gist options
  • Save fabiovila/c6bcadb88bb2a24b8a4dba7ed9040f0b to your computer and use it in GitHub Desktop.
Save fabiovila/c6bcadb88bb2a24b8a4dba7ed9040f0b to your computer and use it in GitHub Desktop.
How send large files with Mongoose with low memory? Send in parts.
static void ev_handler(struct mg_connection *nc, int ev, void *p) {
if (ev == MG_EV_ACCEPT){
nc->user_data = Alloc(3 * sizeof(int)); // My malloc implementation
print("ACCEPT\n",7);
}
if (ev == MG_EV_CLOSE){
AFree(nc->user_data); // Free of malloc implementation
print("CLOSE\n",6);
}
if (ev == MG_EV_SEND){
print("SEND\n",5); // Serial print
#define CHUNKSIZE MG_MAX_HTTP_SEND_MBUF // max buffer size on each tx
int file = ((int *) nc->user_data)[0];
int *pos = &((int *) nc->user_data)[1];
int more = ((int *) nc->user_data)[2];
printf (" %d %d %d \n", file, *pos, more); // printf to serial
if (*pos >= fsFiles[file].size || more == 0) { // fsFiles: See my gist for this virtualfilesystem code
nc->flags |= MG_F_SEND_AND_CLOSE;
} else {
int size = fsFiles[file].size - *pos;
if (size > CHUNKSIZE) mg_send (nc,&fsFiles[file].data[*pos], CHUNKSIZE); else mg_send (nc,&fsFiles[file].data[*pos], size);
*pos = *pos + CHUNKSIZE;
}
}
if (ev == MG_EV_HTTP_REQUEST) {
int Found = 0;
int i = 0;
struct mg_str index = {"/index.html",11};
struct mg_str *uri = 0;
print("HTTP\n",5);
struct http_message *hm = (struct http_message *) p;
if (mg_vcmp(&hm->uri, "/") == 0) uri = &index; else uri = &hm->uri;
for (i =0; i < FS_FILES; i++) {
if (mg_vcmp(uri, fsFiles[i].name) == 0) {
mg_printf(nc, "HTTP/1.1 200 OK\r\nContent-Type: %s\r\nConnection: close\r\nCache-control: private\r\nServer: custom\r\n\r\n", fsFiles[i].mime);
memcpy(nc->user_data, &((int []) {i,0,1}),sizeof(int)*3);
Found = 1;
break;
}
}
if (Found == 0) {
mg_printf(nc, "HTTP/1.1 404 Not Found\r\nConnection: close\r\nCache-control: private\r\nServer: custom\r\n\r\n");
memcpy(nc->user_data, ((int []) {1,0,0}),sizeof(int)*3);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
} // http request
} // ev_handler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment