Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickhutchinson/7761b6f8c11f729434f44fbfd923530c to your computer and use it in GitHub Desktop.
Save nickhutchinson/7761b6f8c11f729434f44fbfd923530c to your computer and use it in GitHub Desktop.
wil::unique_winhttp_hinternet NewMockHandle(function<void(HINTERNET)> onClose) {
using Deleter = function<void(HINTERNET)>;
struct MockHandleCallback {
static __stdcall void mockHandleCallback(HINTERNET hInternet,
DWORD_PTR dwContext,
DWORD dwInternetStatus,
LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength) {
switch (dwInternetStatus) {
case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING:
if (unique_ptr<Deleter> deleter{static_cast<Deleter*>(dwContext)}) {
(*deleter)(hInternet);
}
break;
default:
break;
}
}
};
wil::unique_winhttp_hinternet h{::WinHttpOpen(
L"", WINHTTP_ACCESS_TYPE_NO_PROXY, L"", L"", WINHTTP_FLAG_ASYNC)};
THROW_LAST_ERROR_IF(!h);
THROW_IF_WIN32_BOOL_FALSE(::WinHttpSetStatusCallback(
h.get(), &MockHandleCallback::mockHandleCallback,
WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0));
{
auto deleter = std::make_unique<Deleter>(std::move(onClose));
DWORD_PTR ctx = reinterpret_cast<DWORD_PTR>(deleter.get());
THROW_IF_WIN32_BOOL_FALSE(::WinHttpSetOption(
h.get(), WINHTTP_OPTION_CONTEXT_VALUE, &ctx, sizeof(ctx)));
(void)deleter.release();
}
return h;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment