写点什么

如何用 Go 语言写出好用的 Http 中间件?

  • 2019-08-23
  • 本文字数:2507 字

    阅读完需:约 8 分钟

如何用 Go 语言写出好用的 Http 中间件?

当我们用 Go 语言编写较为复杂的服务时,一个永恒的话题就是中间件。这个话题在网上被一遍一遍又一遍地讨论着。归根结底,中间件应该允许我们:


  1. 拦截 ServeHTTP 调用,并执行任意代码。

  2. 在持续的链上对请求/响应流做变更。

  3. 中断中间件链条,或继续下一个中间件拦截器,最终到真正的请求处理程序上面。


这些听起来跟express.js 中间件很相似。我们研究了许多资料,发现了一些已经存在的解决方案,这些方案跟我们想要的非常吻合,但他们要么有不必要的额外功能,要么需求不对我们的胃口。很明显,我们可以基于express.js编写中间件,安装这个干净整洁的组件之后,20 行以下代码就可以实现一个轻量级的 API

抽象

设计抽象时,首先我们要考虑的就是,如何写中间件函数(从现在起,可以称它为拦截器)。


答案很明显:


它们看起来就像 http.HandlerFunc,带一个额外的参数 next,程序进行下一步的处理。这使得任何人都可以像编写简单函数一样,类似 http.HandlerFunc 这样来编写拦截器,做他们想做的,并能按照他们的意愿传递控制权。


接下来我们要考虑的就是,如何将拦截器挂到http.Handlerhttp.HandlerFunc上。想要达成这个目标,首先要做的就是定义MiddlewareHandlerFunc,简单来说就是http.HandlerFunc的一种类型(例如,type MiddlewareHandlerFunc http.HandlerFunc)。这将让我们在http.HandlerFunc的基础之上,构建一个更好的 API。现在给出一个http.HandlerFunc,我们想要的链式 API 大概是这样:


func HomeRouter(w http.ResponseWriter, r *http.Request) {    // Handle your request}
// ...// Some where when installing Hanlderchain := MiddlewareHandlerFunc(HomeRouter). Intercept(NewElapsedTimeInterceptor()). Intercept(NewRequestIdInterceptor())
// Install it like regular HttpHandlermux.Path("/home").HandlerFunc(http.HandlerFunc(chain))
复制代码


http.HandlerFunc转换成MiddlewareHandlerFunc,并通过调用Intercept方法来安装拦截器。Intercept的返回类型又是一个MiddlewareHandlerFunc,允许我们再次调用Intercept


如果使用Intercept架构,非常值得注意的一点就是执行的先后顺序。因为调用chain(responseWriter, request)实际上就是间接调用上一个拦截器,并将其停止,即从拦截器的尾部回到处理程序的首部。这非常有意义,因为正在拦截调用;所以你应该在父程序前执行拦截。

简化

虽然逆向链式系统让抽象变得更清晰,但大多时候都会有一个预编译拦截数组,可以在不同的处理程序中被复用。另外,当我们把中间件定义为数组时,更倾向按执行顺序去声明这些数组,而不是终止的顺序。我们把这个数组拦截器称作:MiddlewareChain。我们想要的中间件链大概是这样:


注意,这些中间件将按照链中出现的顺序调用,即RequestIDInterceptorElapsedTimeInterceptor。这增加了代码的重用性和可读性。

实现

一旦设计好了抽象内容,实现起来就会很顺利:


/*Copyright (c) 2019 DoorDashPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.*/package middleware
import "net/http"
// MiddlewareInterceptor intercepts an HTTP handler invocation, it is passed both response writer and request// which after interception can be passed onto the handler function.type MiddlewareInterceptor func(http.ResponseWriter, *http.Request, http.HandlerFunc)
// MiddlewareHandlerFunc builds on top of http.HandlerFunc, and exposes API to intercept with MiddlewareInterceptor.// This allows building complex long chains without complicated struct manipulationtype MiddlewareHandlerFunc http.HandlerFunc

// Intercept returns back a continuation that will call install middleware to intercept// the continuation call.func (cont MiddlewareHandlerFunc) Intercept(mw MiddlewareInterceptor) MiddlewareHandlerFunc { return func(writer http.ResponseWriter, request *http.Request) { mw(writer, request, http.HandlerFunc(cont)) }}
// MiddlewareChain is a collection of interceptors that will be invoked in there index ordertype MiddlewareChain []MiddlewareInterceptor
// Handler allows hooking multiple middleware in single call.func (chain MiddlewareChain) Handler(handler http.HandlerFunc) http.Handler { curr := MiddlewareHandlerFunc(handler) for i := len(chain) - 1; i >= 0; i-- { mw := chain[i] curr = curr.Intercept(mw) }
return http.HandlerFunc(curr)}
复制代码


这样一来,20 行(不包括注释)的代码,就能构建一个很不错的中间件库。在裸机上,这几行抽象代码连贯性也是令人惊叹的。这能让我们有条不紊地编写出流畅的 Http 中间件链。希望这几行 Go 语言代码也能给你带来好的中间件体验。


原文链接:


https://doordash.engineering/2019/07/22/writing-delightful-http-middlewares-in-go


2019-08-23 09:007342

评论 1 条评论

发布
用户头像
代码是不完整的,照搬都可以漏。。。
2019-08-27 10:46
回复
没有更多了
发现更多内容

2021Android面试真题精选干货整理,准备Android面试

android 面试 移动开发

2021Android面试题知识点总结,层层深入

android 面试 移动开发

微服务网关Gateway实战

Fox666

微服务 Gateway SpringCloud Gateway Spring Cloud Gateway

大天使之剑H5游戏超详细图文架设教程

echeverra

H5游戏 H5

海量数据,极速体验——TDSQL-A核心架构详解来了 ​

腾讯云数据库

数据库 tdsql

2021Android面试心得,Android详解

android 面试 移动开发

Android技术分享| 一行代码实现安卓屏幕采集编码

anyRTC开发者

音视频 WebRTC 移动开发 Android技术分享 屏幕采集编码

Vite + Vue3 + OpenLayers 手动激活地图

德育处主任

大前端 地图 vite Vue3 openlayers

如何写好倒计时

echeverra

JavaScript

2021Android高级面试题及答案,30岁转行程序员

android 面试 移动开发

2021Android高级面试题总结,憋个大招

android 面试 移动开发

2021BAT大厂Android社招面试题,Android程序员校招蚂蚁金服

android 面试 移动开发

浅析可视化分析技术

郑州埃文科技

2021Android面试笔试总结,这操作真香

android 面试 移动开发

SOA + 汽车智能硬件 = 无限可能

SOA开发者平台

SOA 软件定义汽车

腾讯云 CIF 工程效能峰会,10 月 19 - 20 日震撼来袭!

CODING DevOps

腾讯云 DevOps 云原生 云开发 CIF

CSS中content属性的妙用

echeverra

CSS

2021Android高级面试题,零基础也能看得懂

android 面试 移动开发

2021BAT大厂Android社招面试题,移动开发技术总结

android 面试 移动开发

拓路前行-TDSQL追求极致体验的这一路

腾讯云数据库

数据库 tdsql

2021Android高级面试题及答案,2021最新Android面试题目

android Android面试

TDSQL-C的内核关键技术深入解读

腾讯云数据库

数据库 tdsql

网站URL如何SEO优化

echeverra

SEO

第 2 章 -《Linux 一学就会》- Linux 基本命令操作

学神来啦

Linux 运维 linux云计算

SOA + 汽车智能硬件 = 无限可能

SOA开发者

软件 物联网 SOA 汽车

车路协同赋予交通感知,数字技术让管理透明可视

一只数据鲸鱼

车联网 数据可视化 智慧城市 智慧交通

2021一位Android中级程序员的跳槽面经,成功拿下大厂offer

android 面试 移动开发

2021Android进阶者的新篇章,移动开发框架

android 面试 移动开发

2021Android高级面试题汇总解答,阿里内部Android应届生就业宝典

android 面试 移动开发

2021Android面试心得,透彻解析

android 面试 移动开发

博客被阮一峰引流后,我对“大数据”的分析与思考

echeverra

博客

如何用 Go 语言写出好用的 Http 中间件?_编程语言_Zohaib Sibte Hassan_InfoQ精选文章