Files
sdk/samples/ffi/http/lib/fake_http.cc
T
Liam Appelbe 5354df624a [ffi] NativeCallable.listener example.
Add an example to the NativeCallable.listener documentation.

Bug: https://github.com/dart-lang/sdk/issues/53435
Change-Id: I4b664b14ca1dbc474913a9e191e38ca6f290350f
Fixes: https://github.com/dart-lang/sdk/issues/53435
CoreLibraryReviewExempt: The FFI package is VM-only
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/326580
Reviewed-by: Daco Harkes <dacoharkes@google.com>
Commit-Queue: Liam Appelbe <liama@google.com>
2023-09-22 04:02:20 +00:00

49 lines
1.2 KiB
C++

// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <atomic>
#include <chrono>
#include <cstring>
#include <thread>
#if defined(_WIN32)
#define DART_EXPORT extern "C" __declspec(dllexport)
#else
#define DART_EXPORT \
extern "C" __attribute__((visibility("default"))) __attribute((used))
#endif
constexpr char kExampleRequest[] = R"(
GET / HTTP/1.1
Host: www.example.com
)";
constexpr char kExampleResponse[] = R"(
HTTP/1.1 200 OK
Content-Length: 54
Content-Type: text/html; charset=UTF-8
<html>
<body>
Hello world!
</body>
</html>
)";
DART_EXPORT void http_get(const char* uri, void (*onResponse)(const char*)) {
std::thread([onResponse]() {
std::this_thread::sleep_for(std::chrono::seconds(3));
onResponse(strdup(kExampleResponse));
}).detach();
}
DART_EXPORT void http_serve(void (*onRequest)(const char*)) {
std::thread([onRequest]() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
onRequest(strdup(kExampleRequest));
}
}).detach();
}