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 is a library for building custom HTTP/S proxies



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.


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:



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.


详情可以参考 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 的简单解析,更多的功能需要深入到文档中进行挖掘。