Middleware

Overview

Microservice middleware are software components used to support microservice architecture, they provide some basic functions and services for communication, collaboration and management between microservices, the following middleware is built in go-zero:

  • AuthorizeHandler
  • BreakerHandler
  • ContentSecurityHandler
  • CryptionHandler
  • GunzipHandler
  • LogHandler
  • MaxBytesHandler
  • MaxConnsHandler
  • MetricHandler
  • PrometheusHandler
  • RecoverHandler
  • SheddingHandler
  • TimeoutHandler
  • TraceHandler

The above intermediate is enabled by default. You can also control some of the intermediaries.

Middleware Configuration

  1. type MiddlewaresConf struct {
  2. Trace bool `json:",default=true"`
  3. Log bool `json:",default=true"`
  4. Prometheus bool `json:",default=true"`
  5. MaxConns bool `json:",default=true"`
  6. Breaker bool `json:",default=true"`
  7. Shedding bool `json:",default=true"`
  8. Timeout bool `json:",default=true"`
  9. Recover bool `json:",default=true"`
  10. Metrics bool `json:",default=true"`
  11. MaxBytes bool `json:",default=true"`
  12. Gunzip bool `json:",default=true"`
  13. }
Configuration ItemNoteDefault value
TraceEnable link trackingtrue
LogEnable Log Middlewaretrue
PrometheusWhether to enable Prometheus middlewaretrue
MaxConnsEnable Limit Middlewaretrue
BreakerEnable breaker middlewaretrue
SheddingEnable Load Monitor Middlewaretrue
TimeoutEnable Timeout Middlewaretrue
RecoverEnable Panic Recovery Middlewaretrue
MetricsEnable metrics middlewaretrue
MaxBytesEnable ContentLength Administration Middlewaretrue
GunzipEnable compression management intermediatetrue

For example, if you want to disable indicator collection in the Hello World program, you can configure it as follows:

  • etc/config.yaml
  • main.go
  1. Name: HelloWorld.api
  2. Host: 127.0.0.1
  3. Port: 8080
  4. Middlewares:
  5. Metrics: false
  1. func main() {
  2. var restConf rest.RestConf
  3. conf.MustLoad("etc/config.yaml", &restConf)
  4. srv := rest.MustNewServer(restConf)
  5. defer srv.Stop()
  6. ...
  7. }

Focus Middleware Introduction

TraceHandler

The framework integrates Opentelemetry by default to standardize link tracking.If you want to report the trace information to jaeger, or take the hello world program as an example, you can do the following:

  • etc/config.yaml
  • main.go
  1. Name: HelloWorld.api
  2. Host: 127.0.0.1
  3. Port: 8080
  4. Middlewares:
  5. Metrics: true
  6. Telemetry:
  7. Name: hello
  8. Endpoint: http://127.0.0.1:14268/api/traces
  9. Batcher: jaeger
  10. Sampler: 1.0
  1. var restConf rest.RestConf
  2. conf.MustLoad("etc/config.yaml", &restConf)
  3. srv := rest.MustNewServer(restConf)

Re-request http:///127.0.0.1:8080/helloto view link request information by opening the jaeger page and by defaulthttp.hosthttp.methodhttp.routehttp.status_codeand more.

LogHandler

默认每次 http 请求都会输出对应的请求日志,格式如下:

  1. {
  2. "@timestamp": "2023-03-05T21:53:44.244+08:00",
  3. "caller": "handler/loghandler.go:160",
  4. "content": "[HTTP] 200 - GET /hello - 127.0.0.1:51499 - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36",
  5. "duration": "0.0ms",
  6. "level": "info"
  7. }

Can disable log middleware by configuring it, enabled by default

  • etc/config.yaml
  • main.go
  1. Name: HelloWorld.api
  2. Host: 127.0.0.1
  3. Port: 8080
  4. Middlewares:
  5. Log: false
  1. var restConf rest.RestConf
  2. conf.MustLoad("etc/config.yaml", &restConf)
  3. srv := rest.MustNewServer(restConf)

PrometheusHandler

http server 默认集成了 prometheus 指标监控,指标分别如下:

Requested time-consuming indicator type is Histogram, default label has path,buckets defined as 5, 10, 25, 50, 100, 250, 500, 1000

  1. http_server_requests_duration_ms

Error statistics indicator type is counter, default label has paths, code

  1. http_server_requests_code_total

Prometheus Middleware can be disabled by configuration, enabled by default

  • etc/config.yaml
  • main.go
  1. Name: HelloWorld.api
  2. Host: 127.0.0.1
  3. Port: 8080
  4. Middlewares:
  5. Prometheus: false
  1. var restConf rest.RestConf
  2. conf.MustLoad("etc/config.yaml", &restConf)
  3. srv := rest.MustNewServer(restConf)

MaxConnsHandler

Use to limit the maximum number of requests sent by http:// when the number of concurrent requests exceeds the set value (default is 10,000), when exceeding the setting value returns http.StatusServiceUnav’s status code

Disable is same with above

Custom Middleware

Use Use method to apply custom middleware

  1. server := rest.MustNewServer(rest.RestConf{})
  2. defer server.Stop()
  3. server.Use(middleware)
  4. func middleware(next http.HandlerFunc) http.HandlerFunc {
  5. return func(w http.ResponseWriter, r *http.Request) {
  6. w.Header().Add("X-Middleware", "static-middleware")
  7. next(w, r)
  8. }
  9. }