Example #1
0
int http_send_response(int sockfd, struct HttpResponse *response) {
    debug("http_send_response");
    int status = (response != NULL) ? response->status : 500;
    int content_length = (response != NULL) ? response->content_length : 0;
    const char *payload = (response != NULL) ? response->payload : "";

    char *buf;
    char http_response[] = "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n\r\n%s";
    if (asprintf(&buf, http_response, status, http_reason_phrase(status),
                 content_length, payload) == -1) {
        log_err("An error occurred while creating response.");
        // TODO
        const char* error_response = "HTTP/1.1 500 ERROR\r\n\r\n";
        if (send_all(sockfd, error_response, strlen(error_response), 0) == -1) {
            if (errno == EPIPE) {
                return ERR_BROKEN_PIPE;
            }
            log_err("Send response.");
            exit(-1);
        }
    }
    else {
        if (send_all(sockfd, buf, strlen(buf), 0) == -1) {
            free(buf);
            if (errno == EPIPE) {
                return ERR_BROKEN_PIPE;
            }
            log_err("Send response.");
            exit(-1);
        }
        free(buf);
    }
    return 0;
}
Example #2
0
int http_server_send_vec(struct http_session_t *session, int code, const struct http_vec_t* vec, size_t num, http_server_onsend onsend, void* param)
{
	int r;
	char content_length[32];
	r = http_session_data(session, vec, num);
	if (r < 0) 
		return r;

	// Content-Length
	if (0 == session->http_content_length_flag)
	{
		r = snprintf(content_length, sizeof(content_length), "%d", r);
		http_session_add_header(session, "Content-Length", content_length, r);
	}

	// HTTP Response Header
	r = snprintf(session->status_line, sizeof(session->status_line), "HTTP/1.1 %d %s\r\n", code, http_reason_phrase(code));
	socket_setbufvec(session->vec, 0, session->status_line, r);
	socket_setbufvec(session->vec, 1, session->header, session->header_size);
	socket_setbufvec(session->vec, 2, (void*)s_http_header_end, 2);

	session->onsend = onsend;
	session->onsendparam = param;
	return aio_tcp_transport_send_v(session->transport, session->vec, session->vec_count);
}