URI自定义匹配模板

daya123
Posts: 12
Joined: Fri Jun 25, 2021 7:50 am

URI自定义匹配模板

Postby daya123 » Tue Jul 06, 2021 7:49 am

ESP32做 web服务器使用,使用配置条件:

Code: Select all

config.uri_match_fn = httpd_uri_match_wildcard;
默认可以匹配以xxx开始的部分,匹配如下:

Code: Select all

 * Example:
 *   - * matches everything
 *   - /foo/? matches /foo and /foo/
 *   - /foo/\* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo
 *   - /foo/?* or /foo/\*?  (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo
 *
 * The special characters "?" and "*" anywhere else in the template will be taken literally.
如果我要实现如下这种匹配结构,匹配函数该怎么写?

Code: Select all

 
 /*.html   
 /*.css
文档说,参考httpd_uri_match_func_t函数原型说明
原型如下:

Code: Select all

typedefbool (*httpd_uri_match_func_t)(const char *reference_uri, const char *uri_to_match, size_t match_upto)
Function prototype for URI matching.

Return
true on match

Parameters
[in] reference_uri: URI/template with respect to which the other URI is matched

[in] uri_to_match: URI/template being matched to the reference URI/template

[in] match_upto: For specifying the actual length of uri_to_match up to which the matching algorithm is to be applied (The maximum value is strlen(uri_to_match), independent of the length of reference_uri)
这三个参数的含义没看懂

ESP_YJM
Posts: 300
Joined: Fri Feb 26, 2021 10:30 am

Re: URI自定义匹配模板

Postby ESP_YJM » Wed Jul 07, 2021 3:24 am

第一个参数 reference_uri 代表匹配的模板,可以不带通配符,第二个参数 uri_to_match 代表要匹配的 uri,第三个参数 match_upto 是 第二个参数要匹配的长度,如果全匹配就传入 uri 的长度。
  1. bool esp_http_uri_match_wildcard(const char *template, const char *uri, size_t uri_len)
  2. {
  3.     const size_t tpl_len = strlen(template);
  4.     int tpl_p = 0, uri_p = 0;
  5.     int tpl_p_last = -1, uri_p_last = -1;
  6.  
  7.     while (uri_p < uri_len) {
  8.         if (tpl_p < tpl_len && (*(uri + uri_p) == *(template + tpl_p))) {
  9.             tpl_p ++;
  10.             uri_p ++;
  11.         }
  12.         else if (tpl_p < tpl_len && (*(template + tpl_p) == '*')) {
  13.             tpl_p_last = tpl_p;
  14.             tpl_p ++;
  15.             uri_p_last = uri_p;
  16.         }
  17.         else if (tpl_p_last > -1) {
  18.             tpl_p = tpl_p_last + 1;
  19.             uri_p_last ++;
  20.             uri_p = uri_p_last;
  21.         }
  22.         else {
  23.             return false;
  24.         }
  25.     }
  26.     while (tpl_p < tpl_len && (*(template + tpl_p) == '*')) {
  27.         tpl_p ++;
  28.     }
  29.     if (tpl_p == tpl_len) {
  30.         return true;
  31.     }
  32.     return false;
  33. }
你可以使用上面的函数来匹配你的规则。比如匹配 /*html,函数如下:
  1. esp_http_uri_match_wildcard("*.html", "/test.html", strlen("/test.html"))

Who is online

Users browsing this forum: No registered users and 153 guests