Skip to content

Commit e5db3b5

Browse files
imported wrapper class for url parsing
1 parent 6159db9 commit e5db3b5

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

src/URLParser.h

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
* PackageLicenseDeclared: Apache-2.0
3+
* Copyright (c) 2017 ARM Limited
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
#ifndef _MBED_HTTP_PARSED_URL_H_
19+
#define _MBED_HTTP_PARSED_URL_H_
20+
21+
#include "utility/http_parser.h"
22+
23+
class ParsedUrl {
24+
public:
25+
ParsedUrl(const char* url) {
26+
struct http_parser_url parsed_url;
27+
http_parser_parse_url(url, strlen(url), false, &parsed_url);
28+
29+
for (size_t ix = 0; ix < UF_MAX; ix++) {
30+
char* value;
31+
if (parsed_url.field_set & (1 << ix)) {
32+
value = (char*)calloc(parsed_url.field_data[ix].len + 1, 1);
33+
memcpy(value, url + parsed_url.field_data[ix].off,
34+
parsed_url.field_data[ix].len);
35+
}
36+
else {
37+
value = (char*)calloc(1, 1);
38+
}
39+
40+
switch ((http_parser_url_fields)ix) {
41+
case UF_SCHEMA: _schema = value; break;
42+
case UF_HOST: _host = value; break;
43+
case UF_PATH: _path = value; break;
44+
case UF_QUERY: _query = value; break;
45+
case UF_USERINFO: _userinfo = value; break;
46+
default:
47+
// PORT is already parsed, FRAGMENT is not relevant for HTTP requests
48+
free(value);
49+
break;
50+
}
51+
}
52+
53+
_port = parsed_url.port;
54+
if (!_port) {
55+
if (strcmp(_schema, "https") == 0 || strcmp(_schema, "wss") == 0) {
56+
_port = 443;
57+
}
58+
else {
59+
_port = 80;
60+
}
61+
}
62+
63+
if (strcmp(_path, "") == 0) {
64+
free(_path);
65+
_path = (char*)calloc(2, 1);
66+
_path[0] = '/';
67+
}
68+
}
69+
70+
~ParsedUrl() {
71+
if (_schema) free(_schema);
72+
if (_host) free(_host);
73+
if (_path) free(_path);
74+
if (_query) free(_query);
75+
if (_userinfo) free(_userinfo);
76+
}
77+
78+
uint16_t port() const { return _port; }
79+
char* schema() const { return _schema; }
80+
char* host() const { return _host; }
81+
char* path() const { return _path; }
82+
char* query() const { return _query; }
83+
char* userinfo() const { return _userinfo; }
84+
85+
private:
86+
uint16_t _port;
87+
char* _schema;
88+
char* _host;
89+
char* _path;
90+
char* _query;
91+
char* _userinfo;
92+
};
93+
94+
#endif // _MBED_HTTP_PARSED_URL_H_

0 commit comments

Comments
 (0)