diff options
| author | Nakidai <nakidai@disroot.org> | 2024-11-25 15:13:27 +0300 |
|---|---|---|
| committer | Nakidai <nakidai@disroot.org> | 2024-11-25 15:13:27 +0300 |
| commit | 02c17cbbe441bb15bbab9deccfd8c3dd6c90d4d6 (patch) | |
| tree | cc5f33703190426eb11e5e9ff803746933249f2d | |
| parent | 046d0457b9982fd4eb8cb7521e2a071b03fb3e02 (diff) | |
| download | libhttpc-02c17cbbe441bb15bbab9deccfd8c3dd6c90d4d6.tar.gz libhttpc-02c17cbbe441bb15bbab9deccfd8c3dd6c90d4d6.zip | |
Add LibHTTPC_writeResponse
| -rw-r--r-- | src/response.c | 66 |
1 files changed, 50 insertions, 16 deletions
diff --git a/src/response.c b/src/response.c index 154cd8d..6776da3 100644 --- a/src/response.c +++ b/src/response.c @@ -4,6 +4,30 @@ #include <stdio.h> #include <string.h> +#include <sys/socket.h> + + +#define WRITE() \ + do \ + { \ + append(response->version); \ + append(" "); \ + append(status); \ + append(" "); \ + append(response->phrase); \ + append("\r\n"); \ + for (size_t i = 0; i < response->header_count; ++i) \ + { \ + append(response->headers[i].name); \ + append(": "); \ + append(response->headers[i].value); \ + append("\r\n"); \ + } \ + append("\r\n"); \ + if (response->body) \ + append(response->body); \ + } while (0) + char *LibHTTPC_dumpResponse(struct LibHTTPC_Response *response, char *buf, size_t buf_len) { @@ -19,23 +43,33 @@ char *LibHTTPC_dumpResponse(struct LibHTTPC_Response *response, char *buf, size_ snprintf(status, sizeof(status), "%d", response->status); #define append(X) strncat(buf, (X), buf_len - strlen(buf)) - append(response->version); - append(" "); - append(status); - append(" "); - append(response->phrase); - append("\r\n"); - for (size_t i = 0; i < response->header_count; ++i) - { - append(response->headers[i].name); - append(": "); - append(response->headers[i].value); - append("\r\n"); - } - append("\r\n"); - if (response->body) - append(response->body); + WRITE(); #undef append return NULL; } + +int LibHTTPC_writeResponse(int sockfd, struct LibHTTPC_Response *response) +{ + char status[10]; + + if (!response->version) + response->version = "HTTP/1.1"; + if (!response->status) + response->status = LibHTTPC_Status_OK; + if (!response->phrase) + response->phrase = LibHTTPC_dumpStatus(response->status); + + snprintf(status, sizeof(status), "%d", response->status); + +#define append(X) \ + do \ + { \ + if (send(sockfd, (X), strlen(X), 0) == -1) \ + return 1; \ + } while(0) + WRITE(); +#undef append + + return 0; +} |