Guest User

Untitled

a guest
Oct 17th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <event2/event.h>
  3. #include <event2/http.h>
  4. #include <event2/buffer.h>
  5. #include <hiredis/hiredis.h>
  6. #include <hiredis/async.h>
  7. #include <hiredis/adapters/libevent.h>
  8.  
  9. typedef struct reqData {
  10. struct evhttp_request* req;
  11. struct evbuffer* buf;
  12. } reqData;
  13.  
  14. struct event_base* base;
  15.  
  16. void get_cb(redisAsyncContext* context, void* r, void* data) {
  17. redisReply* reply = r;
  18. struct reqData* rd = data;
  19.  
  20. /* error handling omitted for brevity sake */
  21.  
  22. evbuffer_add_printf(rd->buf, "%s\n", reply->str);
  23. evhttp_send_reply(rd->req, HTTP_OK, NULL, rd->buf);
  24.  
  25. evbuffer_free(rd->buf);
  26. free( rd );
  27. }
  28.  
  29. void cb(struct evhttp_request* req, void* args) {
  30.  
  31. struct evbuffer* buf;
  32. redisAsyncContext* c = (redisAsyncContext *) args;
  33.  
  34. buf = evbuffer_new();
  35.  
  36. /* Uncomment following code to test without any Redis call
  37. evbuffer_add_printf(buf, "toto\n");
  38. evhttp_send_reply(req, HTTP_OK, NULL, buf);
  39. evbuffer_free(buf);
  40. return;
  41. */
  42.  
  43. reqData* rd = malloc(sizeof(reqData));
  44. rd->req = req;
  45. rd->buf = buf;
  46.  
  47. redisAsyncCommand(c, get_cb, rd, "GET name");
  48. }
  49.  
  50. int main(int argc, char** argv) {
  51.  
  52. struct evhttp* http;
  53. struct evhttp_bound_socket* sock;
  54.  
  55. /* Redis connection to be declared and attached to the event loop */
  56. redisAsyncContext* c;
  57. c = redisAsyncConnect("0.0.0.0", 6379);
  58. /* error handling omitted for brevity sake */
  59.  
  60. base = event_base_new();
  61. http = evhttp_new(base);
  62. sock = evhttp_bind_socket_with_handle(http, "0.0.0.0", 8080);
  63.  
  64. redisLibeventAttach(c, base);
  65. evhttp_set_gencb(http, cb, c);
  66.  
  67. event_base_dispatch(base);
  68.  
  69. /* Redis disconnection code omitted */
  70.  
  71. evhttp_free(http);
  72. event_base_free(base);
  73. return 0;
  74. }
Add Comment
Please, Sign In to add comment