Last active
April 22, 2022 13:18
-
-
Save lululombard/18e02439e9a81d4658bddf77ea86104f to your computer and use it in GitHub Desktop.
Brotli/gzip/deflate support for Laravel Vapor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Log; | |
class CompressedResponse | |
{ | |
public function handle(Request $request, Closure $next) | |
{ | |
$response = $next($request); | |
// Most common methods for HTTP compression, from highest to lowest compression | |
$methods = [ | |
'br' => [ | |
'function' => 'brotli_compress', | |
'compression_level' => config('app.brotli_compression_level', 0), | |
], | |
'gzip' => [ | |
'function' => 'gzencode', | |
'compression_level' => config('app.gzip_compression_level', 9), | |
], | |
'deflate' => [ | |
'function' => 'gzdeflate', | |
'compression_level' => config('app.deflate_compression_level', 9), | |
] | |
]; | |
// Try all methods in order | |
foreach ($methods as $method => $method_data) { | |
if (in_array($method, $request->getEncodings()) && function_exists($method_data['function'])) { | |
try { | |
// Call compression function | |
$response->setContent( | |
$method_data['function']( | |
$response->getContent(), | |
$method_data['compression_level'] | |
) | |
); | |
// Set headers for content encoding and binary response | |
// https://docs.vapor.build/1.0/projects/development.html#binary-responses | |
$response->headers->add([ | |
'Content-Encoding' => $method, | |
'X-Vapor-Base64-Encode' => 'True', | |
]); | |
return $response; | |
} catch (\Exception $e) { | |
Log::warning('Compression using ' . $method . ' failed: ' . $e->getMessage()); | |
} | |
} | |
} | |
// Return response if no compatible compression method was found, but log just in case | |
Log::warning('No compression method found for encodings [' . implode(', ', $request->getEncodings()) . '] for request: ' . $request->getRequestUri()); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment