Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Gohttp Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation

    composer require dcarbone/gohttp
    

    No service provider needed—use the facade directly.

  2. 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');
    
  3. 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)

Implementation Patterns

1. Middleware Chains (Go-Style)

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']);
});

2. Routing with 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');

3. Request/Response Handling

$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]);
});

4. Laravel Integration (Custom HTTP Server)

// 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');
}

5. Testing HTTP Logic

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));
}

6. CLI HTTP Tools

// 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');

Gotchas and Tips

Pitfalls

  1. No Laravel Facade

    • Unlike Laravel’s Http, gohttp has no built-in facade. Use use DCarbone\GoHttp\Http\Server; directly.
  2. Middleware Incompatibility

    • gohttp middleware does not integrate with Laravel’s Illuminate\Pipeline. Use only for standalone HTTP servers.
  3. Request Object Differences

    • gohttp\Request lacks Laravel’s magic methods (e.g., $request->user()). Parse manually:
      $userId = $req->Header.Get('X-User-ID');
      
  4. No PSR-15 Support

    • Middleware must implement gohttp's Middleware interface, not PSR-15. Example:
      class AuthMiddleware implements Middleware {
          public function Handle($req, $res, $next) { ... }
      }
      
  5. PHP 7.0+ Only

    • No support for PHP 8+ features (e.g., typed properties, attributes). May need polyfills.
  6. No Built-in Testing Helpers

    • Use Guzzle or PHP’s curl to test endpoints, as gohttp lacks Laravel’s Http::fake().

Debugging Tips

  1. 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);
    }));
    
  2. Check Headers Manually

    • gohttp doesn’t auto-set Content-Type for JSON. Add explicitly:
      $res->Header.Set('Content-Type', 'application/json');
      
  3. Handle Errors Gracefully

    • Wrap server logic in try-catch:
      try {
          $server->ListenAndServe(':8080');
      } catch (\Exception $e) {
          \Log::error('Server error:', ['error' => $e->getMessage()]);
      }
      

Extension Points

  1. Custom Handlers

    • Extend Handler interface for non-HandleFunc logic:
      class CustomHandler implements Handler {
          public function ServeHTTP($req, $res) { ... }
      }
      
  2. Add Go-Like Features

    • Implement Go’s http.Error pattern:
      $res->WriteHeader(404);
      $res->Write([]); // Empty body for 404
      
  3. Integrate with Laravel’s Request

    • Bridge gohttp\Request to Laravel’s Illuminate\Http\Request:
      $laravelRequest = new \Illuminate\Http\Request([
          'input' => $req->Form,
          'query' => $req->URL.Query,
      ]);
      

Performance Quirks

  • Connection Pooling: gohttp lacks Go’s http.Client pooling. For high traffic, use Laravel’s HttpClient instead.
  • Memory Leaks: Reuse Server/Request objects in loops to avoid GC overhead:
    $server = new Server();
    while (true) {
        $server->Serve($req, $res); // Reuse objects
    }
    

Laravel-Specific Workarounds

  1. 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');
        }
    }
    
  2. Avoid in Web Routes

    • gohttp is not a drop-in replacement for Laravel’s routing. Use only for:
      • CLI tools
      • Background jobs with HTTP servers
      • Non-web contexts (e.g., API gateways)
  3. Mocking for Tests

    • Use PHP’s Mockery to stub Server/Request:
      $mockServer = Mockery::mock(Server::class);
      $mockServer->shouldReceive('ListenAndServe')->once();
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor