Advertisement
Guest User

Untitled

a guest
Sep 29th, 2012
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. // router.h
  2.  
  3. #ifndef WN_ROUTE_H
  4. #define WN_ROUTE_H
  5.  
  6. #include <stdlib.h>
  7.  
  8. typedef enum {
  9.     GET,
  10.     POST,
  11.     PUT,
  12.     DELETE,
  13. } wn_method;
  14.  
  15. typedef struct {
  16.     wn_method method;
  17.     char *path;
  18. } wn_context;
  19.  
  20. typedef void (*wn_handler)(wn_context *);
  21.  
  22. typedef struct {
  23.     wn_method method;
  24.     char *regex;
  25.     wn_handler handler;
  26. } wn_route;
  27.  
  28. wn_handler wn_get_handler(wn_method method, char *path,
  29.                           wn_route *routes, size_t routes_len);
  30.  
  31. #endif
  32.  
  33. // router.c
  34.  
  35. #include <regex.h>
  36.  
  37. wn_handler wn_get_handler(wn_method method, char *path,
  38.                           wn_route *routes, size_t routes_len) {
  39.     int err;
  40.     regex_t regex;
  41.     regcomp(&regex, "^$", 0); // Make the first regfree call work without UB.
  42.    
  43.     for (size_t i = 0; i < routes_len; ++i) {
  44.         if (routes[i].method != method) continue;
  45.        
  46.         regfree(&regex);
  47.         err = regcomp(&regex, routes[i].regex, 0);
  48.         if (err > 0) continue; // fuck this shit
  49.        
  50.         int match = regexec(&regex, path, 0, NULL, 0);
  51.         switch (match) {
  52.             case 0:
  53.                 regfree(&regex);
  54.                 return routes[i].handler;
  55.             case REG_NOMATCH: continue;
  56.             default: continue; // fuck this shit
  57.         }
  58.     }
  59.    
  60.     regfree(&regex);
  61.     return NULL;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement