Golang如何实现简单的API网关


本文摘自php中文网,作者藏色散人,侵删。

下面由Golang教程栏目给大家介绍Golang实现简单的API网关的方法 ,希望对需要的朋友有所帮助!

在最近的一个项目中,采用了微服务架构-go-kit进行后端的开发。在微服务架构风格中,一个大应用被拆分成为了多个小的服务系统提供出来,这些小的系统他们可以自成体系,也就是说这些小系统可以拥有自己的数据库,框架甚至语言等,因此我们需要设计一个API 网关(API Gataway),其实网上已经有较多现成的实现框架,但是本项目的需求是比较简单的,因此将使用Golang自行实现。

实现

API网关是一个服务器,是系统的唯一入口。从面向对象设计的角度看,它与外观模式类似。API网关封装了系统内部架构,为每个客户端提供一个定制的API。它可能还具有其它职责,如身份验证、监控、负载均衡、缓存、请求分片与管理、静态响应处理。

用于实现API网关的技术有很多,大致分为这么几类:

  • 通用反向代理:NginxHaproxy、……
  • 网络编程框架:NettyServlet、……
  • API网关框架:Spring Cloud GatewayZuulZuul2、……

API网关最基本的功能就是反向代理。其实现方式有很多,本文将基于标准库net/http/httputil包中的ReverseProxy类型来实现实现一个简单的反向代理。反向代理的实现主要涉及到func NewSingleHostReverseProxy(target *url.URL) *ReverseProxytype ReverseProxy

1

func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

// NewSingleHostReverseProxy returns a new ReverseProxy that routes// URLs to the scheme, host, and base path provided in target. If the// target's path is "/base" and the incoming request was for "/dir",// the target request will be for /base/dir.// NewSingleHostReverseProxy does not rewrite the Host header.// To rewrite Host headers, use ReverseProxy directly with a custom// Director policy.func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {

    targetQuery := target.RawQuery

    director := func(req *http.Request) {

        req.URL.Scheme = target.Scheme

        req.URL.Host = target.Host

        req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)

        if targetQuery == "" || req.URL.RawQuery == "" {

            req.URL.RawQuery = targetQuery + req.URL.RawQuery       } else {

            req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery     }

        if _, ok := req.Header["User-Agent"]; !ok {

            // explicitly disable User-Agent so it's not set to default value

            req.Header.Set("User-Agent", "")

        }

    }

    return &ReverseProxy{Director: director}}

NewSingleHostReverseProxy返回一个新的ReverseProxy,将URLs请求路由到targe的指定的scheme, host, base path

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

// ReverseProxy is an HTTP Handler that takes an incoming request and// sends it to another server, proxying the response back to the// client.type ReverseProxy struct {

    // Director must be a function which modifies

    // the request into a new request to be sent

    // using Transport. Its response is then copied

    // back to the original client unmodified.

    // Director must not access the provided Request

    // after returning.

    Director func(*http.Request)

 

    Transport http.RoundTripper

 

    FlushInterval time.Duration

 

    ErrorLog *log.Logger

 

    BufferPool BufferPool   // ModifyResponse is an optional function that modifies the

    // Response from the backend. It is called if the backend

    // returns a response at all, with any HTTP status code.

    // If the backend is unreachable, the optional ErrorHandler is

    // called without any call to ModifyResponse.

    //

    // If ModifyResponse returns an error, ErrorHandler is called

    // with its error value. If ErrorHandler is nil, its default

    // implementation is used.

    ModifyResponse func(*http.Response) error

 

    ErrorHandler func(http.ResponseWriter, *http.Request, error)}

ReverseProxy类型有两个重要的属性,分别是DirectorModifyResponse,这两个属性都是函数类型,在接收到客户端请求时,ServeHTTP函数首先调用Director函数对接受到的请求体进行修改,例如修改请求的目标地址、请求头等;然后使用修改后的请求体发起新的请求,接收到响应后,调用ModifyResponse函数对响应进行修改,最后将修改后的响应体拷贝并响应给客户端,这样就实现了反向代理的整个流程。

阅读剩余部分

相关阅读 >>

go设计模式之工厂模式浅谈

图文讲解godoc的安装与使用

golang有类(class)吗?

golang语言社区--游戏服务器编程说明

[go] go语言实战-基于websocket浏览器通知的实现

golang 是面向对象的么

[go-linq]-go的.net linq式查询方法

gin(6)-模板渲染

关于golang当中对select的理解

go - 切片

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...