OpenSwoole HTTP Client Helper Functions

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

The helper request functions allow you to make one off HTTP requests quickly and easily, they are useful for when you don't need the full power of the HTTP client.

There are 3 main functions and they are request(), post() and get().


Take a look at the full example below:

<?php

use function OpenSwoole\Coroutine\go;
use function OpenSwoole\Coroutine\Http\get;
use function OpenSwoole\Coroutine\Http\post;
use function OpenSwoole\Coroutine\Http\request;

// Main coroutine context
co::run(function()
{
    // Coroutine 1
    go(function()
    {
        $data = get('http://httpbin.org/get?hello=world');
        $body = json_decode($data->getBody());
        assert($body->headers->Host === 'httpbin.org');
        assert($body->args->hello === 'world');
    });

    // Coroutine 2
    go(function()
    {
        $random_data = base64_encode(random_bytes(128));
        $data = post('http://httpbin.org/post?hello=world', ['random_data' => $random_data]);
        $body = json_decode($data->getBody());
        assert($body->headers->Host === 'httpbin.org');
        assert($body->args->hello === 'world');
        assert($body->form->random_data === $random_data);
    });
});
Last updated on September 1, 2022