GoLang Martian lib 之应用解析(一)

前段时间阅读 KrakenD(https://www.krakend.io)的代码,发现KrakenD的代码中,使用了gin(https://gin-gonic.github.io/gin/)作为http(s)的route engine,使用了google发布的Martian (https://github.com/google/martian)作为proxy engine,结合前端时间写过的一个小业务层proxy项目,就非常感兴趣的对Martian做一些了解。

Martian(https://github.com/google/martian)是google发布的用来做proxy的lib:

Martian is a library for building custom HTTP/S proxies

那么Martian都支持什么样的功能呢?

从google发布这个lib的本意来讲,其目的是为了“testing”:

Martian Proxy is a programmable HTTP proxy designed to be used for testing.

Martian is a great tool to use if you want to:

  • Verify that all (or some subset) of requests are secure

  • Mock external services at the network layer

  • Inject headers, modify cookies or perform other mutations of HTTP requests and responses

  • Verify that pingbacks happen when you think they should

  • Unwrap encrypted traffic (requires install of CA certificate in browser)

By taking advantage of Go cross-compilation, Martian can be deployed anywhere that Go can target.

可以通过下面的方式来快速实现一个proxy的功能:

Start the Proxy

Assuming you've installed Martian, running the proxy is as simple as

By default, Martian will be running on port 8080, and the Martian API will be running on 8181 . The port can be specified via flags:

除此之外,Martian还支持HAR格式的logging

Logging

For logging of requests and responses a [logging modifier](https://github.com/google/martian/wiki/Modifier-Reference#logging) is available or [HAR](http://www.softwareishard.com/blog/har-12-spec/) logs are available if the -har flag is used.

最为强大的是,Martian支持强大的配置,在proxy的过程中,来修改request和response:

详情可以参考 https://github.com/google/martian/wiki/Modifier-Reference

最为可贵的是:

Martian can also be included into any Go program and used as a library. 这也是KrakenD选择Martian作为后端proxy的一个关键原因。

Modifiers All The Way Down

Martian's request and response modification system is designed to be general and extensible. The design objective is to provide individual modifier behaviors that can arranged to build out nearly any desired modification.

When working with Martian to compose behaviors, you'll need to be familiar with these different types of interactions:

  • Modifiers: Changes the state of a request or a response

  • Filters: Conditionally allows a contained Modifier to execute

  • Groups: Bundles multiple modifiers to be executed in the order specified in the group

  • Verifiers: Tracks network traffic against expectations

Modifiers, filters and groups all implement RequestModifer, ResponseModifier or RequestResponseModifier (defined inmartian.go).

这是一个非常有价值的功能,对于部分中台业务来讲,对请求以及响应内容的过滤、修改、组合等逻辑往往会是强需求,在不修改中台后端服务模型(请求、响应)的情况下,对中台接口输出结果进行调整,只输出必要的内容,或是通过修正响应内容,兼容前端的需求。

上面是对 martian lib 的简单解析,更多的功能需要深入到文档中进行挖掘。

此条目发表在GoLang, MircroService分类目录。将固定链接加入收藏夹。