首页 » 后端 » Laravel » 正文

API url 的 header 中添加版本信息(Laravel)

发布者:站点默认
2022/04/12 浏览数(400) 分类:Laravel API url 的 header 中添加版本信息(Laravel)已关闭评论

.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;
  }
}
相关文章
点击返回顶部
  1. 留言
  2. 联系方式