当前位置:网站首页>Gorilla/mux framework (RK boot): add tracing Middleware
Gorilla/mux framework (RK boot): add tracing Middleware
2022-07-03 22:49:00 【dongxuny】
Introduce
Through a complete example , Based on gorilla/mux Add call chain to microservice (Tracing) middleware .
What is a call chain (Tracing) middleware ?
Call chain (Tracing) Middleware will be used for every API Request record Tracing data , Users can use something like Jaeger Tool View .
We will use rk-boot To start up gorilla/mux Microservices . rk-boot It's a pass through YAML Start multiple Web Service framework . Please refer to the last chapter of this article , understand rk-boot details .
Please visit the following address for a complete tutorial :https://github.com/rookie-ninja/rk-mux
install
go get github.com/rookie-ninja/rk-boot/mux
Quick start
rk-boot By default OpenTelemetry-CNCF To deal with it Tracing.
1. establish boot.yaml
In order to verify , We launched the following options :
- commonService:commonService It contains a series of general API. details
- jaeger exporter:gorilla/mux The service will be delivered locally jaeger agent send data .
---mux: - name: greeter # Required port: 8080 # Required enabled: true # Required commonService: enabled: true # Optional, default: false interceptors: tracingTelemetry: enabled: true # Optional, Enable tracing interceptor/middleware exporter: jaeger: agent: enabled: true # Optional, Export to jaeger agent
2. establish main.go
add to /v1/greeter API.
// Copyright (c) 2021 rookie-ninja//// Use of this source code is governed by an Apache-style// license that can be found in the LICENSE file.package mainimport ( "context" "fmt" "github.com/rookie-ninja/rk-boot" "github.com/rookie-ninja/rk-boot/mux" "github.com/rookie-ninja/rk-mux/interceptor" "github.com/rookie-ninja/rk-mux/interceptor/context" "net/http")func main() { // Create a new boot instance. boot := rkboot.NewBoot() // Register handler entry := rkbootmux.GetMuxEntry("greeter") entry.Router.NewRoute().Methods(http.MethodGet).Path("/v1/greeter").HandlerFunc(Greeter) // Bootstrap boot.Bootstrap(context.TODO()) boot.WaitForShutdownSig(context.TODO())}func Greeter(writer http.ResponseWriter, request *http.Request) { rkmuxinter.WriteJson(writer, http.StatusOK, &GreeterResponse{ Message: fmt.Sprintf("Hello %s!", request.URL.Query().Get("name")), })}type GreeterResponse struct { Message string}
3. Folder structure
$ tree.├── boot.yaml├── go.mod├── go.sum└── main.go0 directories, 4 files
4. Local boot jaeger
$ docker run -d --name jaeger \ -e COLLECTOR_ZIPKIN_HOST_PORT=:9411 \ -p 5775:5775/udp \ -p 6831:6831/udp \ -p 6832:6832/udp \ -p 5778:5778 \ -p 16686:16686 \ -p 14268:14268 \ -p 14250:14250 \ -p 9411:9411 \ jaegertracing/all-in-one:1.23
5. start-up main.go
$ go run main.go
6. verification
- Send a request to CommonService Inside /rk/v1/healthy API.
$ curl -X GET localhost:8080/rk/v1/healthy{"healthy":true}
- Send a request to /v1/greeter API.
$ curl -X GET "localhost:8080/v1/greeter?name=rk-dev"{"Message":"Hello rk-dev!"}
- visit jaeger Home page : http://localhost:16686/
Not through rkentry.GlobalAppCtx.GetAppInfoEntry().AppName Appoint AppName Under the circumstances , By default rk As AppName.
Output to Stdout
It can be modified by boot.yaml File to modify the output path , such as STDOUT.
- boot.yaml
---mux: - name: greeter # Required port: 8080 # Required enabled: true # Required commonService: enabled: true # Optional, default: false interceptors: tracingTelemetry: enabled: true # Optional, Enable tracing interceptor/middleware exporter: file: enabled: true outputPath: "stdout" # Optional, Output to stdout
output to a file
It can be modified by boot.yaml File to save Tracing Information to file .
- boot.yaml
---mux: - name: greeter # Required port: 8080 # Required enabled: true # Required commonService: enabled: true # Optional, default: false interceptors: tracingTelemetry: enabled: true # Optional, Enable tracing interceptor/middleware exporter: file: enabled: true outputPath: "logs/tracing.log" # Optional, Log to files
YAML Options
name | describe | type | The default value is |
---|---|---|---|
mux.interceptors.tracingTelemetry.enabled | Start the call chain interceptor | boolean | false |
mux.interceptors.tracingTelemetry.exporter.file.enabled | Start file output | boolean | false |
mux.interceptors.tracingTelemetry.exporter.file.outputPath | Output file path | string | stdout |
mux.interceptors.tracingTelemetry.exporter.jaeger.agent.enabled | jaeger agent Output as data | boolean | false |
mux.interceptors.tracingTelemetry.exporter.jaeger.agent.host | jaeger agent Address | string | localhost |
mux.interceptors.tracingTelemetry.exporter.jaeger.agent.port | jaeger agent port | int | 6831 |
mux.interceptors.tracingTelemetry.exporter.jaeger.collector.enabled | jaeger collector Output as data | boolean | false |
mux.interceptors.tracingTelemetry.exporter.jaeger.collector.endpoint | jaeger collector Address | string | http://localhost:16368/api/trace |
mux.interceptors.tracingTelemetry.exporter.jaeger.collector.username | jaeger collector user name | string | "" |
mux.interceptors.tracingTelemetry.exporter.jaeger.collector.password | jaeger collector password | string | "" |
rk-boot Introduce
rk-boot It's a pass through YAML Start multiple Web Service framework . It's kind of like Spring boot. Through integration rk-xxx Series Library , Can start a variety of Web frame . Of course , Users can also customize rk-xxx The library is integrated into rk-boot in .
rk-boot Bright spot
Through the same format YAML file , Start different Web frame .
such as , We can use the following documents , Start simultaneously in one process gRPC, Gin, Echo, GoFrame frame . Unify the micro service layout within the team .
- Dependent installation
go get github.com/rookie-ninja/rk-boot/grpcgo get github.com/rookie-ninja/rk-boot/gingo get github.com/rookie-ninja/rk-boot/echogo get github.com/rookie-ninja/rk-boot/gf
- boot.yaml
---grpc: - name: grpc-server port: 8080 enabled: true commonService: enabled: truegin: - name: gin-server port: 8081 enabled: true commonService: enabled: trueecho: - name: echo-server port: 8082 enabled: true commonService: enabled: truegf: - name: gf-server port: 8083 enabled: true commonService: enabled: true
- main.go
// Copyright (c) 2021 rookie-ninja//// Use of this source code is governed by an Apache-style// license that can be found in the LICENSE file.package mainimport ( "context" "github.com/rookie-ninja/rk-boot" _ "github.com/rookie-ninja/rk-boot/echo" _ "github.com/rookie-ninja/rk-boot/gf" _ "github.com/rookie-ninja/rk-boot/gin" _ "github.com/rookie-ninja/rk-boot/grpc")// Application entrance.func main() { // Create a new boot instance. boot := rkboot.NewBoot() // Bootstrap boot.Bootstrap(context.Background()) // Wait for shutdown sig boot.WaitForShutdownSig(context.Background())}
- verification
# gRPC throuth grpc-gateway$ curl localhost:8080/rk/v1/healthy{"healthy":true}# Gin$ curl localhost:8081/rk/v1/healthy{"healthy":true}# Echo$ curl localhost:8082/rk/v1/healthy{"healthy":true}# GoFrame$ curl localhost:8083/rk/v1/healthy{"healthy":true}
rk-boot Supported by Web frame
Welcome to contribute new Web Frame to rk-boot In the series .
Reference resources docs & rk-gin As an example .
frame | Development status | install | rely on |
---|---|---|---|
Gin | Stable | go get github.com/rookie-ninja/rk-boot/gin | rk-gin |
gRPC | Stable | go get github.com/rookie-ninja/rk-boot/grpc | rk-grpc |
Echo | Stable | go get github.com/rookie-ninja/rk-boot/echo | rk-echo |
GoFrame | Stable | go get github.com/rookie-ninja/rk-boot/gf | rk-gf |
Fiber | Testing | go get github.com/rookie-ninja/rk-boot/fiber | rk-fiber |
go-zero | Testing | go get github.com/rookie-ninja/rk-boot/zero | rk-zero |
GorillaMux | Testing | go get github.com/rookie-ninja/rk-boot/mux | rk-mux |
rk-mux Introduce
rk-mux Used by YAML start-up gorilla/mux Web service .
Supported features
according to YAML The file initializes the following example , If it's external , Keep the original usage .
example | Introduce |
---|---|
mux.Router | Native gorilla/mux |
Config | Native spf13/viper Parameter instance |
Logger | Native uber-go/zap Log instance |
EventLogger | Used to record RPC Request log , Use rk-query |
Credential | For remote services , for example ETCD Pull Credential |
Cert | From remote service (ETCD wait ) In order to get TLS/SSL certificate , And start the SSL/TLS |
Prometheus | start-up Prometheus client , And push it to pushgateway |
Swagger | Local boot Swagger UI |
CommonService | Exposure general API |
TV | TV Webpage , Show the basic information of microservices |
StaticFileHandler | start-up Web Form of static file download service , Background storage supports local file systems and pkger. |
Supported middleware
rk-mux Will be based on YAML File initialization middleware .
Middleware | Description |
---|---|
Metrics | collect RPC Metrics, And start the prometheus |
Log | Use rk-query Record each RPC journal |
Trace | collect RPC Call chain , And send data to stdout, Local files or jaeger open-telemetry/opentelemetry-go. |
Panic | Recover from panic for RPC requests and log it. |
Meta | Collect service meta information , Add to return Header in |
Auth | Support [Basic Auth] & [API Key] Verification middleware |
RateLimit | RPC Speed limiting middleware |
Timeout | RPC Timeout |
CORS | CORS middleware |
JWT | JWT verification |
Secure | Server side security middleware |
CSRF | CSRF middleware |
Mux complete YAML To configure
---#app:# description: "this is description" # Optional, default: ""# keywords: ["rk", "golang"] # Optional, default: []# homeUrl: "http://example.com" # Optional, default: ""# iconUrl: "http://example.com" # Optional, default: ""# docsUrl: ["http://example.com"] # Optional, default: []# maintainers: ["rk-dev"] # Optional, default: []#zapLogger:# - name: zap-logger # Required# description: "Description of entry" # Optional#eventLogger:# - name: event-logger # Required# description: "Description of entry" # Optional#cred:# - name: "local-cred" # Required# provider: "localFs" # Required, etcd, consul, localFs, remoteFs are supported options# description: "Description of entry" # Optional# locale: "*::*::*::*" # Optional, default: *::*::*::*# paths: # Optional# - "example/boot/full/cred.yaml"#cert:# - name: "local-cert" # Required# provider: "localFs" # Required, etcd, consul, localFs, remoteFs are supported options# description: "Description of entry" # Optional# locale: "*::*::*::*" # Optional, default: *::*::*::*# serverCertPath: "example/boot/full/server.pem" # Optional, default: "", path of certificate on local FS# serverKeyPath: "example/boot/full/server-key.pem" # Optional, default: "", path of certificate on local FS# clientCertPath: "example/client.pem" # Optional, default: "", path of certificate on local FS# clientKeyPath: "example/client.pem" # Optional, default: "", path of certificate on local FS#config:# - name: rk-main # Required# path: "example/boot/full/config.yaml" # Required# locale: "*::*::*::*" # Required, default: *::*::*::*# description: "Description of entry" # Optionalmux: - name: greeter # Required port: 8080 # Required enabled: true # Required# description: "greeter server" # Optional, default: ""# cert:# ref: "local-cert" # Optional, default: "", reference of cert entry declared above# sw:# enabled: true # Optional, default: false# path: "sw" # Optional, default: "sw"# jsonPath: "" # Optional# headers: ["sw:rk"] # Optional, default: []# commonService:# enabled: true # Optional, default: false# static:# enabled: true # Optional, default: false# path: "/rk/v1/static" # Optional, default: /rk/v1/static# sourceType: local # Required, options: pkger, local# sourcePath: "." # Required, full path of source directory# tv:# enabled: true # Optional, default: false# prom:# enabled: true # Optional, default: false# path: "" # Optional, default: "metrics"# pusher:# enabled: false # Optional, default: false# jobName: "greeter-pusher" # Required# remoteAddress: "localhost:9091" # Required# basicAuth: "user:pass" # Optional, default: ""# intervalMs: 10000 # Optional, default: 1000# cert: # Optional# ref: "local-test" # Optional, default: "", reference of cert entry declared above# logger:# zapLogger:# ref: zap-logger # Optional, default: logger of STDOUT, reference of logger entry declared above# eventLogger:# ref: event-logger # Optional, default: logger of STDOUT, reference of logger entry declared above# interceptors:# loggingZap:# enabled: true # Optional, default: false# zapLoggerEncoding: "json" # Optional, default: "console"# zapLoggerOutputPaths: ["logs/app.log"] # Optional, default: ["stdout"]# eventLoggerEncoding: "json" # Optional, default: "console"# eventLoggerOutputPaths: ["logs/event.log"] # Optional, default: ["stdout"]# metricsProm:# enabled: true # Optional, default: false# auth:# enabled: true # Optional, default: false# basic:# - "user:pass" # Optional, default: []# ignorePrefix:# - "/rk/v1" # Optional, default: []# apiKey:# - "keys" # Optional, default: []# meta:# enabled: true # Optional, default: false# prefix: "rk" # Optional, default: "rk"# tracingTelemetry:# enabled: true # Optional, default: false# exporter: # Optional, default will create a stdout exporter# file:# enabled: true # Optional, default: false# outputPath: "logs/trace.log" # Optional, default: stdout# jaeger:# agent:# enabled: false # Optional, default: false# host: "" # Optional, default: localhost# port: 0 # Optional, default: 6831# collector:# enabled: true # Optional, default: false# endpoint: "" # Optional, default: http://localhost:14268/api/traces# username: "" # Optional, default: ""# password: "" # Optional, default: ""# rateLimit:# enabled: false # Optional, default: false# algorithm: "leakyBucket" # Optional, default: "tokenBucket"# reqPerSec: 100 # Optional, default: 1000000# paths:# - path: "/rk/v1/healthy" # Optional, default: ""# reqPerSec: 0 # Optional, default: 1000000# jwt:# enabled: true # Optional, default: false# signingKey: "my-secret" # Required# ignorePrefix: # Optional, default: []# - "/rk/v1/tv"# - "/sw"# - "/rk/v1/assets"# signingKeys: # Optional# - "key:value"# signingAlgo: "" # Optional, default: "HS256"# tokenLookup: "header:<name>" # Optional, default: "header:Authorization"# authScheme: "Bearer" # Optional, default: "Bearer"# secure:# enabled: true # Optional, default: false# xssProtection: "" # Optional, default: "1; mode=block"# contentTypeNosniff: "" # Optional, default: nosniff# xFrameOptions: "" # Optional, default: SAMEORIGIN# hstsMaxAge: 0 # Optional, default: 0# hstsExcludeSubdomains: false # Optional, default: false# hstsPreloadEnabled: false # Optional, default: false# contentSecurityPolicy: "" # Optional, default: ""# cspReportOnly: false # Optional, default: false# referrerPolicy: "" # Optional, default: ""# ignorePrefix: [] # Optional, default: []# csrf:# enabled: true# tokenLength: 32 # Optional, default: 32# tokenLookup: "header:X-CSRF-Token" # Optional, default: "header:X-CSRF-Token"# cookieName: "_csrf" # Optional, default: _csrf# cookieDomain: "" # Optional, default: ""# cookiePath: "" # Optional, default: ""# cookieMaxAge: 86400 # Optional, default: 86400# cookieHttpOnly: false # Optional, default: false# cookieSameSite: "default" # Optional, default: "default", options: lax, strict, none, default# ignorePrefix: [] # Optional, default: []
边栏推荐
- Programming language (1)
- 540. Single element in ordered array
- What indicators should be paid attention to in current limit monitoring?
- Ppt image processing
- 33 restrict the input of qlineedit control (verifier)
- Unsafe and CAS principle
- LeetCode 1646. Get the maximum value in the generated array
- The reason why the computer runs slowly and how to solve it
- Yyds dry goods inventory Prometheus alarm Art
- Leetcode week 4: maximum sum of arrays (shape pressing DP bit operation)
猜你喜欢
This time, thoroughly understand bidirectional data binding 01
What are the common computer problems and solutions
The overseas listing of Shangmei group received feedback, and brands such as Han Shu and Yiye have been notified for many times and received attention
Hcip day 12 notes
Scratch uses runner Py run or debug crawler
Data consistency between redis and database
Firefox set up proxy server
Programming language (2)
Bluebridge cup Guoxin Changtian single chip microcomputer -- hardware environment (I)
Hcip day 15 notes
随机推荐
How does sentinel, a traffic management artifact, make it easy for business parties to access?
Hcip day 16 notes
Niuke winter vacation training camp 4 g (enumeration optimization, Euler power reduction)
How to solve the problem of requiring a password when accessing your network neighborhood on your computer
Covariance
540. Single element in ordered array
Recursion and recursion
JarPath
6.2 normalization 6.2.5 third normal form (3NF)
Go Technology Daily (2022-02-13) - Summary of experience in database storage selection
Morning flowers and evening flowers
[golang] leetcode intermediate - alphabetic combination of island number and phone number
Buuctf, misc: n solutions
Mindmanager2022 serial number key decompression installer tutorial
LeetCode 1647. Minimum deletion times of unique character frequency
Unsafe and CAS principle
股票炒股开户注册安全靠谱吗?有没有风险的?
Bluebridge cup Guoxin Changtian single chip microcomputer -- hardware environment (I)
[sg function]split game (2020 Jiangxi university student programming competition)
How can enterprises and developers take advantage of the explosion of cloud native landing?