completed send response function

This commit is contained in:
Win 2024-05-23 19:31:49 +07:00
parent 76f17729b4
commit 78a0eb6854
2 changed files with 22 additions and 17 deletions

BIN
server

Binary file not shown.

View File

@ -14,12 +14,11 @@ int send_response(int fd, char *header, char *content_type, void *body, int cont
const int max_response_size = 65536; const int max_response_size = 65536;
char response[max_response_size]; char response[max_response_size];
time_t rawtime; time_t current = time(NULL);
struct tm *info; char date_time[30];
strftime(date_time, sizeof(date_time), "%a, %d %b %Y %H:%M:%S %Z", localtime(&current));
info = localtime(&rawtime);
int header_length = sprintf(response,
int response_length = sprintf(response,
"%s\n" "%s\n"
"Server: %s\n" "Server: %s\n"
"Date: %s\n" "Date: %s\n"
@ -27,19 +26,24 @@ int send_response(int fd, char *header, char *content_type, void *body, int cont
"Content-Length: %d\n" "Content-Length: %d\n"
"Content-Type: %s\n" "Content-Type: %s\n"
"\n", "\n",
header, SERVER_VERSION, asctime(info), content_length, content_type); header, SERVER_VERSION, date_time, content_length, content_type);
memcpy(response + response_length, body, content_length); printf("%s\n", (char *)body);
//printf("%p\n", (char *)response);
//printf("%p\n", &header_length);
//printf("%p\n", (void *)(response + header_length));
memcpy(response + header_length, body, content_length);
printf("%s\n", response); printf("%s\n", response);
write(fd, response, response_length); int write_res = write(fd, response, header_length + content_length);
if (write_res < 0) {
perror("webserver (write)");
return write_res;
}
//if (write < 0) { return write_res;
// perror("webserver (write)");
// return write;
//}
return 0;
} }
int main() { int main() {
@ -147,8 +151,9 @@ int main() {
// } // }
char body[100]; char body[100];
int body_size = snprintf(body, 100, "%s\r\n", "hello"); int body_size = snprintf(body, 100, "%s\r\n", "hello what up bruh");
send_response(newsockfd, "HTTP/1.1 200 OK", "text/html", "deeznuts", sizeof(body_size)); printf("%d\n", body_size);
send_response(newsockfd, "HTTP/1.1 200 OK", "text/html", body, (body_size+1));
} }
// write to the socket // write to the socket