推薦一個強大的 Go 庫 - rk-boot

我是一隻可愛的土撥鼠,專注於分享 Go 職場、招聘和求職,解 Gopher 之憂!歡迎關注我。

歡迎大家加入 Go 招聘交流羣,來這裏找志同道合的小夥伴!跟土撥鼠們一起交流學習。

rk-boot 的介紹

通過 rk-boot,用戶可以通過 yaml 格式的配置文件啓動 gRPC、gin、echo、GoFrame、prometheus 客戶端或自定義入口服務。很容易易編譯、運行和調試你的 grpc 服務、grpc 網關、swagger UI 和 rk-tv Web UI。

爲什麼我們需要它?

在我們公司項目中,各個部門的項目結構都不統一,甚至一個小組內都不會很統一,這種情況數不勝數(儘管用了框架規範)。

下圖是使用 rk-boot 的圖示

arch

Gin 的示例

這裏土撥鼠只舉了關於 gin 的例子,跟其他組件例子 (gRPC、echo、GoFrame、prometheus) 相比,只是 boot.yaml 配置不同。這裏 gin 會引用 rk-gin 的 boot[1] 包。

目錄結構

├── boot.yaml
└── main.go

boot.yaml

---
gin:
  - name: greeter       # Required, Name of gin entry 服務名稱
    port: 8080          # Required, Port of gin entry 端口號
    enabled: true       # Required, Enable gin entry 是否啓用gin
    sw:
      enabled: true     # Optional, Enable swagger UI 是否啓用swagger
    commonService:
      enabled: true     # Optional, Enable common service 是否啓用commonService
    tv:
      enabled:  true    # Optional, Enable RK TV 是否啓用RK TV

main.go

package main

import (
   "context"
   "github.com/rookie-ninja/rk-boot"
)

func main() {
   // 創建rkboot實例 -- Create a new boot instance.
   boot := rkboot.NewBoot()

   // 啓動rkboot -- Bootstrap
   boot.Bootstrap(context.Background())

   // 等待接受關閉信號 -- Wait for shutdown sig
   boot.WaitForShutdownSig(context.Background())
}

運行 && 請求

$ go run main.go
$ curl -X GET localhost:8080/rk/v1/healthy
{"healthy":true}

Swagger

可以通過 http://localhost:8080/sw 訪問 swagger 頁面

TV

可以通過 http://localhost:8080/rk/v1/tv 訪問 TV 頁面

開啓中間件

其中 rk-boot 依賴的 rk-grpc[2]、rk-gin[3] 集成了很多中間件,可以在 boot.yaml 中配置使用,下面是在 gin 的示例中開啓了日誌 zap 的使用,可以通過訪問curl -X GET localhost:8080/rk/v1/healthy查看日誌。

gin:
  - name: greeter                             # Required
    port: 8080                                # Required
    enabled: true                             # Required
    commonService:                            # Optional
      enabled: true                           # Optional, default: false
    interceptors:                             # Optional
      loggingZap:
        enabled: true

另外還支持以下中間件,中間件源碼包 interceptor[4] 可以按需開啓使用。對應的示例可以查看 example[5]。

小結

rk-boot 還支持 gRPC 代理目前還在試驗階段,相信後續會有更多功能支持。土撥鼠今天介紹這個庫主要是覺得這種可配置化、定製的思想很值得在企業項目中借鑑和落地。還可以統一一些公共組件的使用,節省大量成本。如果你有相關看法,歡迎大家在留言區討論交流。

參考資料

[1]

boot: https://github.com/rookie-ninja/rk-gin/tree/master/boot

[2]

rk-grpc: https://github.com/rookie-ninja/rk-grpc

[3]

rk-gin: https://github.com/rookie-ninja/rk-gin

[4]

interceptor: https://github.com/rookie-ninja/rk-gin/tree/master/interceptor

[5]

example: https://github.com/rookie-ninja/rk-gin/tree/master/example

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/2v-4Z3Ew4DRq17SWGas63A