Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // router.h
- #ifndef WN_ROUTE_H
- #define WN_ROUTE_H
- #include <stdlib.h>
- typedef enum {
- GET,
- POST,
- PUT,
- DELETE,
- } wn_method;
- typedef struct {
- wn_method method;
- char *path;
- } wn_context;
- typedef void (*wn_handler)(wn_context *);
- typedef struct {
- wn_method method;
- char *regex;
- wn_handler handler;
- } wn_route;
- wn_handler wn_get_handler(wn_method method, char *path,
- wn_route *routes, size_t routes_len);
- #endif
- // router.c
- #include <regex.h>
- wn_handler wn_get_handler(wn_method method, char *path,
- wn_route *routes, size_t routes_len) {
- int err;
- regex_t regex;
- regcomp(®ex, "^$", 0); // Make the first regfree call work without UB.
- for (size_t i = 0; i < routes_len; ++i) {
- if (routes[i].method != method) continue;
- regfree(®ex);
- err = regcomp(®ex, routes[i].regex, 0);
- if (err > 0) continue; // fuck this shit
- int match = regexec(®ex, path, 0, NULL, 0);
- switch (match) {
- case 0:
- regfree(®ex);
- return routes[i].handler;
- case REG_NOMATCH: continue;
- default: continue; // fuck this shit
- }
- }
- regfree(®ex);
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement