forked from cpv-project/cpv-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpForm.hpp
91 lines (77 loc) · 2.36 KB
/
HttpForm.hpp
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
#pragma once
#include "../Allocators/StackAllocator.hpp"
#include "../Utility/Packet.hpp"
namespace cpv {
/**
* Class used to parse and build url encoded form
*
* Example (url encoded):
* a=1&b=2&b=3
* ```
* formParameters: { "a": [ "1" ], b: [ "2", "3" ] }
* ```
*
* Notice:
* Duplicated form parameter is supported, you can use getMany() to get all values,
* or use get() to get the first value.
* For performance reason, form parser will ignore all errors.
*
* TODO: add parseMultipart and buildMultipart, may require layout change for files.
*/
class HttpForm {
public:
using ValuesType = StackAllocatedVector<SharedString, 1>;
using FormParametersType = StackAllocatedMap<SharedString, ValuesType, 8>;
/** Get all values */
const FormParametersType& getAll() const& { return formParameters_; }
FormParametersType& getAll() & { return formParameters_; }
/**
* Get the first value associated with given key.
* return empty if key not exists.
*/
SharedString get(const SharedString& key) const {
auto it = formParameters_.find(key);
if (it != formParameters_.end() && !it->second.empty()) {
return it->second.front().share();
}
return SharedString();
}
/**
* Get values associated with given key.
* return a static empty vector if key not exists.
*/
const ValuesType& getMany(const SharedString& key) const& {
auto it = formParameters_.find(key);
return (it != formParameters_.end()) ? it->second : Empty;
}
/**
* Add value associated with given key.
* Call it multiple times can associate multiple values with the same key.
*/
void add(SharedString&& key, SharedString&& value) {
formParameters_[std::move(key)].emplace_back(std::move(value));
}
/** Remove values associated with given key */
void remove(const SharedString& key) {
formParameters_.erase(key);
}
/** Remove all values */
void clear() {
formParameters_.clear();
}
/** Parse url encoded form body */
void parseUrlEncoded(const SharedString& body);
/** Apend url encoded form body to packet */
void buildUrlEncoded(Packet& packet);
/** Constructor */
HttpForm();
/** Construct with url encoded form body */
explicit HttpForm(const SharedString& body) : HttpForm() {
parseUrlEncoded(body);
}
private:
static const ValuesType Empty;
private:
FormParametersType formParameters_;
};
}