userver: /data/code/userver/libraries/easy/samples/2_key_value/main.cpp Source File
Loading...
Searching...
No Matches
main.cpp
1#include <userver/utest/using_namespace_userver.hpp> // Note: this is for the purposes of samples only
2
3#include <userver/easy.hpp>
4
5constexpr std::string_view kSchema = R"~(
6CREATE TABLE IF NOT EXISTS key_value_table (
7 key VARCHAR PRIMARY KEY,
8 value VARCHAR
9)
10)~";
11
12int main(int argc, char* argv[]) {
13 easy::HttpWith<easy::PgDep>(argc, argv)
14 .DbSchema(kSchema)
15 .Get(
16 "/kv",
17 [](const server::http::HttpRequest& req, const easy::PgDep& dep) {
18 auto res = dep.pg().Execute(
19 storages::postgres::ClusterHostType::kSlave,
20 "SELECT value FROM key_value_table WHERE key=$1",
21 req.GetArg("key")
22 );
23 return res[0][0].As<std::string>();
24 }
25 )
26 .Post(
27 "/kv",
28 [](const server::http::HttpRequest& req, const auto& dep) {
29 dep.pg().Execute(
30 storages::postgres::ClusterHostType::kMaster,
31 "INSERT INTO key_value_table(key, value) VALUES($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2",
32 req.GetArg("key"),
33 req.GetArg("value")
34 );
35 return std::string{};
36 }
37 )
38 .DefaultContentType(http::content_type::kTextPlain);
39}