-
Notifications
You must be signed in to change notification settings - Fork 21
/
sg_router.c
90 lines (85 loc) · 2.71 KB
/
sg_router.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* _
* ___ __ _ __ _ _ _(_)
* / __|/ _` |/ _` | | | | |
* \__ \ (_| | (_| | |_| | |
* |___/\__,_|\__, |\__,_|_|
* |___/
*
* Cross-platform library which helps to develop web servers or frameworks.
*
* Copyright (C) 2016-2020 Silvio Clecio <[email protected]>
*
* Sagui library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Sagui library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sagui library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <errno.h>
#include "sg_macros.h"
#include "utlist.h"
#include "sg_routes.h"
#include "sg_router.h"
#include "sagui.h"
struct sg_router *sg_router_new(struct sg_route *routes) {
struct sg_router *router;
if (!routes) {
errno = EINVAL;
return NULL;
}
router = sg_alloc(sizeof(struct sg_router));
if (!router)
return NULL;
router->routes = routes;
return router;
}
void sg_router_free(struct sg_router *router) {
sg_free(router);
}
int sg_router_dispatch2(struct sg_router *router, const char *path,
void *user_data, sg_router_dispatch_cb dispatch_cb,
void *cls, sg_router_match_cb match_cb) {
struct sg_route *route;
int ret;
if (!router || !path || !router->routes)
return EINVAL;
LL_FOREACH(router->routes, route) {
if (dispatch_cb) {
ret = dispatch_cb(cls, path, route);
if (ret != 0)
return ret;
}
#ifdef PCRE2_JIT_SUPPORT
#define SG__PCRE2_MATCH pcre2_jit_match
#else /* PCRE2_JIT_SUPPORT */
#define SG__PCRE2_MATCH pcre2_match
#endif /* PCRE2_JIT_SUPPORT */
route->rc = SG__PCRE2_MATCH(route->re, (PCRE2_SPTR) path, strlen(path), 0,
0, route->match, NULL);
#undef SG__PCRE2_MATCH
if (route->rc >= 0) {
route->path = path;
route->user_data = user_data;
if (match_cb) {
ret = match_cb(cls, route);
if (ret != 0)
return ret;
}
route->cb(route->cls, route);
return 0;
}
}
return ENOENT;
}
int sg_router_dispatch(struct sg_router *router, const char *path,
void *user_data) {
return sg_router_dispatch2(router, path, user_data, NULL, NULL, NULL);
}