newline chop
+50 −12 · 2 files changed
-
graph/sockets/http_server.c+21 −12 -
graph/sockets/s.h+29 −0
@@ -8,13 +8,11 @@ #include <setjmp.h> // for jump #include <sys/types.h> #include <sys/socket.h> +#include "s.h" // ---------------------------------------------------------------- -typedef struct __attribute__((packed)){ - uint64_t len; - char *data; -} String; + // ---------------------------------------------------------------- //#define PORT 6969 @@ -66,13 +64,24 @@ void handleRequest(int fd) { if (requestBufSize < 0) { requestError(strerror(errno)); } - // Add a newline as read does not add a newline. - char newline = '\n'; - - write(STDOUT_FILENO,requestBuffer,(size_t) requestBufSize); - write(STDOUT_FILENO,&newline,1); - - fprintf (stderr, "* Size of buffer is: %zd bytes\n",requestBufSize); + String buffer = { + .len = (uint16_t) requestBufSize, + .data = requestBuffer + }; + String line; + + buffer = chop_line(buffer, &line); + + fprintf (stderr, "* Size of buffer is: %zd bytes\n",buffer.len); + while (buffer.len != 0 && line.len != 0) { + char newline = '\n'; + char bar = '|'; + write(STDOUT_FILENO,&bar,1); + write(STDOUT_FILENO,line.data,line.len); + write(STDOUT_FILENO,&bar,1); + write(STDOUT_FILENO,&newline,1); + buffer = chop_line(buffer, &line); + } } // ---------------------------------------------------------------- @@ -155,7 +164,7 @@ int main (int argc, char **argv) { fprintf(stderr, "Could not send data %s\n", strerror(errno)); } // close the connection - err = shutdown(client_fd,SHUT_WR); + err = close(client_fd); if (err < 0) { fprintf(stderr, "Could not close client connection from %s\n", strerror(errno)); } @@ -0,0 +1,29 @@ +#ifndef S_H_ +#define S_H_ + +typedef struct __attribute__((packed)) { + uint64_t len; + char *data; +} String; + +static inline +String chop_line(String input, String *line) { + uint64_t i = 0; + while (i < input.len && input.data[i] != '\n'){ + ++i; + } + line->data = input.data; + line->len = i; + + if (i == input.len) { + input.data += input.len; + input.len = 0; + } else { + input.data += i + 1; + input.len -= i + 1; + } + + return input; +} + +#endif // S_H_ \ No newline at end of file