example.c (1395B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define HTTPP_IMPLEMENTATION 5 #include "httpp.h" 6 7 char* req = 8 "POST /api/items HTTP/1.1\r\n" 9 "Host: api.example.com\r\n" 10 "User-Agent: MyClient/1.0\r\n" 11 "Content-Type: application/json\r\n" 12 "Content-Length: 48\r\n" 13 "\r\n" 14 "{\"name\":\"Widget\",\"quantity\":10,\"price\":9.99}"; 15 16 int main() 17 { 18 httpp_req_t* parsed = httpp_parse_request(req); 19 printf("%s\n", parsed->body); // parsed, malloc'd body 20 printf("%i\n", parsed->method); // Method is an enum! 21 22 const char* method = httpp_method_to_string(parsed->method); // Method as string (e.g POST) 23 printf("%s\n", method); 24 25 httpp_header_t* host = httpp_find_header(parsed, "Host"); 26 printf("%s\n", host->value); // api.example.com 27 28 httpp_res_t* response = httpp_res_new(); 29 response->code = Ok; // or 200 30 httpp_add_header(response, "Host", "somehost.some.where"); 31 httpp_add_header(response, "Status", "ok"); 32 33 httpp_res_set_body(response, "Some body"); 34 char* raw = httpp_res_to_raw(response); // Convert to a malloc'd raw string 35 36 printf("\nComposed response: \n"); 37 printf("----\n%s\n----\n", raw); // Or write it to a socket 38 39 // Don't forget to free everything 40 httpp_req_free(parsed); // Free parsed request 41 httpp_res_free(response); // Free response structure 42 free(raw); // Free composed raw response 43 }