.env
APP_VERSION=v2.0.1 beta
app/Http/Kernel.php
protected $middleware = [ // ... \App\Http\Middleware\Version::class, // 在 http header 中返回当前接口的 Git 版本 ];
app/Http/Middleware/Version.php
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class Version { /** * 在 header 中添加项目 Git 库的 commit id * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { $gitCommitId = '-1'; // 如果 .env 配置有 APP_VERSION 则使用这个 $gitRepoFolder = base_path() .'/.git'; $isGitRepo = file_exists($gitRepoFolder); $appVersion = env('APP_VERSION'); if ($appVersion) { $gitCommitId = $appVersion; } // 如果源码是 git 库,则取当前分支的最新 commit id elseif ($isGitRepo) { $gitHead = trim(file_get_contents("$gitRepoFolder/HEAD")); $gitRef = str_replace('ref: ', '', $gitHead); $gitBranch = basename($gitRef); $gitCommitId = trim(file_get_contents("$gitRepoFolder/$gitRef")); $gitCommitId = "$gitBranch/$gitCommitId"; } $response = $next($request); $response->headers->set('version', $gitCommitId); return $response; } }