dcarbone/gohttp
Small PHP helper library inspired by Go’s net/http. Provides lightweight, Go-style utilities to simplify common HTTP request/response tasks in PHP, aiming to “PHP-ize” a few useful pieces of the Golang HTTP package.
Installation
composer require dcarbone/gohttp
No service provider needed—use the facade directly.
First Use Case: HTTP Server
use DCarbone\GoHttp\Http\Server;
$server = new Server();
$server->HandleFunc('/', function ($req, $res) {
$res->Write([]); // Simple JSON response
});
$server->ListenAndServe(':8080');
Key Classes to Explore
DCarbone\GoHttp\Http\Server (HTTP server)DCarbone\GoHttp\Http\Request (request parsing)DCarbone\GoHttp\Http\Response (response formatting)DCarbone\GoHttp\Http\ServeMux (router)use DCarbone\GoHttp\Http\Middleware;
$server = new Server();
$server->Use(Middleware::func(function ($req, $res, $next) {
// Pre-processing (e.g., auth)
$next($req, $res);
// Post-processing
}));
$server->HandleFunc('/', function ($req, $res) {
$res->Write(['message' => 'Hello']);
});
ServeMux$mux = new ServeMux();
$mux->HandleFunc('/users', function ($req, $res) {
$res->Write(['users' => User::all()]);
});
$mux->HandleFunc('/health', function ($req, $res) {
$res->Write(['status' => 'ok']);
});
$server = new Server();
$server->Handler = $mux;
$server->ListenAndServe(':8000');
$server->HandleFunc('/data', function ($req, $res) {
// Parse query params
$id = $req->URL.Query.Get('id');
// Parse JSON body
$data = json_decode($req->Body, true);
// Write response
$res->Header.Set('Content-Type', 'application/json');
$res->Write(['id' => $id, 'data' => $data]);
});
// In a Laravel command or Artisan tool
public function handle()
{
$server = new Server();
$server->HandleFunc('/api', function ($req, $res) {
$res->Write(['data' => User::find(1)]);
});
$server->ListenAndServe(':3000');
}
public function testServer()
{
$server = new Server();
$server->HandleFunc('/test', function ($req, $res) {
$res->Write(['success' => true]);
});
$client = new \GuzzleHttp\Client();
$response = $client->get('http://localhost:8080/test');
$this->assertEquals(['success' => true], json_decode($response->getBody(), true));
}
// Standalone CLI tool (e.g., `php proxy.php`)
$server = new Server();
$server->HandleFunc('/proxy', function ($req, $res) {
$external = @file_get_contents($req->URL.String());
$res->Write($external);
});
$server->ListenAndServe(':9090');
No Laravel Facade
Http, gohttp has no built-in facade. Use use DCarbone\GoHttp\Http\Server; directly.Middleware Incompatibility
gohttp middleware does not integrate with Laravel’s Illuminate\Pipeline. Use only for standalone HTTP servers.Request Object Differences
gohttp\Request lacks Laravel’s magic methods (e.g., $request->user()). Parse manually:
$userId = $req->Header.Get('X-User-ID');
No PSR-15 Support
gohttp's Middleware interface, not PSR-15. Example:
class AuthMiddleware implements Middleware {
public function Handle($req, $res, $next) { ... }
}
PHP 7.0+ Only
No Built-in Testing Helpers
curl to test endpoints, as gohttp lacks Laravel’s Http::fake().Log Requests/Responses
$server->Use(Middleware::func(function ($req, $res, $next) {
\Log::info('Request:', $req->URL.String());
$next($req, $res);
\Log::info('Response:', $res->Status);
}));
Check Headers Manually
gohttp doesn’t auto-set Content-Type for JSON. Add explicitly:
$res->Header.Set('Content-Type', 'application/json');
Handle Errors Gracefully
try {
$server->ListenAndServe(':8080');
} catch (\Exception $e) {
\Log::error('Server error:', ['error' => $e->getMessage()]);
}
Custom Handlers
Handler interface for non-HandleFunc logic:
class CustomHandler implements Handler {
public function ServeHTTP($req, $res) { ... }
}
Add Go-Like Features
http.Error pattern:
$res->WriteHeader(404);
$res->Write([]); // Empty body for 404
Integrate with Laravel’s Request
gohttp\Request to Laravel’s Illuminate\Http\Request:
$laravelRequest = new \Illuminate\Http\Request([
'input' => $req->Form,
'query' => $req->URL.Query,
]);
gohttp lacks Go’s http.Client pooling. For high traffic, use Laravel’s HttpClient instead.Server/Request objects in loops to avoid GC overhead:
$server = new Server();
while (true) {
$server->Serve($req, $res); // Reuse objects
}
Use in Artisan Commands
use DCarbone\GoHttp\Http\Server;
class ProxyCommand extends Command {
public function handle() {
$server = new Server();
$server->HandleFunc('/proxy', function ($req, $res) {
$res->Write(file_get_contents($req->URL.String()));
});
$server->ListenAndServe(':9000');
}
}
Avoid in Web Routes
gohttp is not a drop-in replacement for Laravel’s routing. Use only for:
Mocking for Tests
Mockery to stub Server/Request:
$mockServer = Mockery::mock(Server::class);
$mockServer->shouldReceive('ListenAndServe')->once();
How can I help you explore Laravel packages today?