GolangNote

Golang笔记

使用fasthttp 做高性能的网关

Permalink

fasthttp 的性能是标准库的10+ 倍,用来做简单网关、微服务是个很好的选择。

使用fasthttp 做高性能的网关

这里是用 fasthttp 来做一个简单的网关,使用场景是应用通过网关访问多个微服务,使微服务的接口不暴露,也可以在网关做更多的认证操作。

Go: fasthttp 高性能网关
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main

import (
	"flag"
	"log"

	"github.com/valyala/fasthttp"
)

var (
	proxyAddr   string
	proxyClient = &fasthttp.HostClient{
		IsTLS: false,
		Addr:  "",
		// set other options here if required - most notably timeouts.
		// ReadTimeout: 60, // 如果在生产环境启用会出现多次请求现象
	}
)

func ReverseProxyHandler(ctx *fasthttp.RequestCtx) {
	req := &ctx.Request
	resp := &ctx.Response

	prepareRequest(req)

	if err := proxyClient.Do(req, resp); err != nil {
		ctx.Logger().Printf("error when proxying the request: %s", err)
	}

	postprocessResponse(resp)
}

func prepareRequest(req *fasthttp.Request) {
	// do not proxy "Connection" header.
	req.Header.Del("Connection")
	// strip other unneeded headers.

	// alter other request params before sending them to upstream host
	req.Header.SetHost(proxyAddr)
}

func postprocessResponse(resp *fasthttp.Response) {
	// do not proxy "Connection" header
	resp.Header.Del("Connection")

	// strip other unneeded headers

	// alter other response data if needed
	// resp.Header.Set("Access-Control-Allow-Origin", "*")
	// resp.Header.Set("Access-Control-Request-Method", "OPTIONS,HEAD,POST")
	// resp.Header.Set("Content-Type", "application/json; charset=utf-8")
}

func main() {
	port := flag.String("port", "8082", "listen port")
	targetAddr := flag.String("target", "api.yourdomain.com", "your server domain")
	flag.Parse()

	proxyClient.Addr = *targetAddr

	log.Println("port:", *port)
	log.Println("target:", *targetAddr)

	if err := fasthttp.ListenAndServe("localhost:"+*port, ReverseProxyHandler); err != nil {
		log.Fatalf("error in fasthttp server: %s", err)
	}
}

fasthttp https://github.com/valyala/fasthttp

Related articles

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

bolt 使用示例

bolt 是一款高性能的key value 数据库,下面是它的使用示例:...

Write a Comment to "使用fasthttp 做高性能的网关"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.5 Processed in 1ms