Skip to content

Add support to directly send binary data in http reply #3012

@achillis2016

Description

@achillis2016

Hello, thanks so much for your hard work on this project mongoose, I love it .

Sometimes I need to directly send binary data in http reply, but I found it hard.
I know the data length before send ,so I don't want to use mg_http_write_chunk。
I have to build http response header by myself,but function mg_http_status_code_str is not exposed.

What I want is a function as below:

void mg_http_reply_binary(struct mg_connection *c, int code,const char *headers,
	const char *buf, size_t len) {
	mg_printf(c, "HTTP/1.1 %d %s\r\n%sContent-Length: %d\r\n\r\n", code,
		mg_http_status_code_str(code), headers == NULL ? "" : headers, len);

	mg_send(c, buf, len);
	c->is_resp = 0;
}

then I can use this function to directly send binary data as response :

void handler(struct mg_connection *c, int ev, void *ev_data) 
{
	if (ev != MG_EV_HTTP_MSG) return ;
	
	struct mg_http_message *hm = (struct mg_http_message *)ev_data;
	
	if (mg_match(hm->uri, mg_str("/bin"), NULL)) 
	{
		unsigned char data[8] = {'A','B', 0, 'C', 'D'};  //notice that there is a \x00 in data
		mg_http_reply_binary(c, 200, "Content-Type: application/octet-stream\r\n", (const char*)data, 5);
		return;
	}
	else
	{
		mg_http_reply(c,404,"","no matched uri");
	}
}

Otherwise, the function mg_http_status_code_str is very helpful, I suggest that this function can be exposed, just add a declare in mongoose.h and remove the word "static" before the function body.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions