<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          構(gòu)建微服務(wù)的十大 Go 框架/庫

          共 12981字,需瀏覽 26分鐘

           ·

          2021-03-03 09:01

          點(diǎn)擊上方藍(lán)色“Go語言中文網(wǎng)”關(guān)注,每天一起學(xué) Go

          現(xiàn)在,很多開源庫都支持構(gòu)建應(yīng)用程序。我應(yīng)該向你推薦一些庫,它們可以幫助啟動具有簡單設(shè)計(jì)、干凈代碼和良好性能的項(xiàng)目。

          01 CLI 命令(spf13/cobra)

          你想要構(gòu)建一些 CLI 命令嗎?

          Cobra 既是一個(gè)用于創(chuàng)建強(qiáng)大的現(xiàn)代 CLI 應(yīng)用程序的庫,也是一個(gè)用于生成應(yīng)用程序和命令文件的程序。

          我使用這個(gè)庫來管理命令應(yīng)用程序,執(zhí)行運(yùn)行程序,初始化配置,并啟動 Rest API。

          基于 cobra 的應(yīng)用組織結(jié)構(gòu):

          ├── app
          │ ├── main.go
          │ ├── cmd
          │ └── root.go

          app/main.go 的代碼如下:

          package main
          import (
             "app/cmd"
          )
          func main() {
             cmd.Execute()
          }

          app/cmd/root.go 代碼如下:

          package cmd
          var rootCmd = &cobra.Command{
             Use:   "hugo",
             Short: "Hugo is a very fast static site generator",
             Long: `A Fast and Flexible Static Site Generator built with love by spf13 and friends in Go. Complete documentation is available at http://hugo.spf13.com`,
             Run: func(cmd *cobra.Command, args []string) {
                // Do Stuff Here
             },
          }
          func Execute() {
             if err := rootCmd.Execute(); err != nil {
                fmt.Println(err)
                os.Exit(1)
             }
          }

          項(xiàng)目地址:https://github.com/spf13/cobra。

          02 配置讀取器(spf13/viper)

          Viper 是 Go 應(yīng)用程序的完整配置解決方案。

          Viper 支持以下格式配置:

          • JSON
          • TOML
          • YAML
          • HCL
          • INI
          • envfile
          • Java properties config files

          例如 config/config.toml:

          address="localhost"
          port="9090"

          響應(yīng)操作的文件 config.go:

          func ReadConfig() {
             viper.SetConfigName("config/config.toml")
             viper.SetConfigType("toml")
             err := viper.ReadInConfig()
             if err != nil {
                panic(fmt.Errorf("Fatal error config file: %s \n", err))
             }
          }

          然后在 main.go 中使用 config 的值:

          func main() {
             address := viper.Get("address")
             port := viper.Get("port")
             fmt.Printf("address: %s", address)
             fmt.Printf("port: %s", port)
          }

          項(xiàng)目地址:https://github.com/spf13/viper。

          03 Web 框架(labstack/echo)

          Echo 是一個(gè)高性能、極簡主義的 Go Web 框架。

          安裝

          // go get github.com/labstack/echo/{version}
          go get github.com/labstack/echo/v4

          例子

          package main

          import (
            "net/http"
            "github.com/labstack/echo/v4"
            "github.com/labstack/echo/v4/middleware"
          )

          func main() {
            // Echo instance
            e := echo.New()

            // Middleware
            e.Use(middleware.Logger())
            e.Use(middleware.Recover())

            // Routes
            e.GET("/", hello)

            // Start server
            e.Logger.Fatal(e.Start(":1323"))
          }

          // Handler
          func hello(c echo.Context) error {
            return c.String(http.StatusOK, "Hello, World!")
          }

          項(xiàng)目地址:https://github.com/labstack/echo。

          04 依賴注入(uber-go/fx)

          我發(fā)現(xiàn)這個(gè)庫非常有用,你不需要生成任何東西。只有代碼。非常模塊化和清晰的層次。

          一個(gè)依賴注入的 Go 應(yīng)用框架。

          func main() {
           fx.New(injectModule()).Run()
          }

          func injectModule() fx.Option {
           return fx.Options(
            fx.Provide( 
                 NewTimeOutContext, 
                 NewDbConn, 
            ),
            repository.Module, 
            service.Module, 
            outbound.Module, 
            server.Module, 
            controller.Module,
           )
          }

          項(xiàng)目地址:https://github.com/uber-go/fx。

          04 Swagger Generator, UI 和 Validation

          在 swagger 部分,我必須使用不同的 3 個(gè)庫,因?yàn)槲覜]有找到 1 個(gè)庫同時(shí)包含這個(gè) 3 個(gè)庫功能的。如果你有推薦,請?jiān)u論告知。

          a、Swagger generator (swaggo/swag)

          Swag 將 Go 注釋轉(zhuǎn)換為 Swagger Documentation 2.0。

          我們?yōu)榱餍械?Go Webb 框架[1]創(chuàng)建了各種各樣的插件。這允許你快速集成一個(gè)現(xiàn)有的 Go 項(xiàng)目(使用 Swagger UI)。

          支持的 Web 框架:

          • gin
          • echo
          • buffalo
          • net/http

          Swag 已經(jīng)處理了你那些 swagger 文件。所以你不再需要寫 swagger.yml 或 swagger.json。你需要做的只是編寫注釋。看一個(gè)例子:

          // @title Blueprint Swagger API
          // @version 1.0
          // @description Swagger API for Golang Project Blueprint.
          // @termsOfService http://swagger.io/terms/
          // @contact.name API Support
          // @contact.email [email protected]
          // @license.name MIT
          // @license.url https://github.com/MartinHeinz/go-project-blueprint/blob/master/LICENSE
          // @BasePath /api/v1
          func main() {
              ...
              r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
              ...
          }

          項(xiàng)目地址:https://github.com/swaggo/swag。

          b、Swagger UI (swaggo/echo-swagger)

          因?yàn)槲艺谑褂?echo,所以我為 swagger 選擇了這個(gè) user interface。

          使用示例:

          package main
          import (
           "github.com/labstack/echo/v4"
           "github.com/swaggo/echo-swagger"
           _ "github.com/swaggo/echo-swagger/example/docs" // docs is generated by Swag CLI, you have to import it.
          )
          // @title Swagger Example API
          // @version 1.0
          // @description This is a sample server Petstore server.
          // @termsOfService http://swagger.io/terms/
          // @contact.name API Support
          // @contact.url http://www.swagger.io/support
          // @contact.email [email protected]
          // @license.name Apache 2.0
          // @license.url http://www.apache.org/licenses/LICENSE-2.0.html
          // @host petstore.swagger.io
          // @BasePath /v2
          func main() {
           e := echo.New()
           e.GET("/swagger/*", echoSwagger.WrapHandler)
           e.Logger.Fatal(e.Start(":1323"))
          }

          項(xiàng)目地址:https://github.com/swaggo/echo-swagger。

          c、Swagger validation (go-swagger/go-swagger)

          這個(gè)包包含了 Swagger 2.0(又名 OpenAPI 2.0[2])的 golang 實(shí)現(xiàn): 它知道如何序列化和反序列化 Swagger 規(guī)范。

          安裝:

          go get github.com/go-swagger/go-swagger/cmd/swagger

          運(yùn)行以驗(yàn)證:

          swagger validate api/docs/swagger.yaml

          輸出如下:

          2021/01/30 22:47:01 
          The swagger spec at "api/docs/swagger.yaml" is valid against swagger specification 2.0

          項(xiàng)目地址:https://github.com/go-swagger/go-swagger。

          06、自定義 Logger (sirupsen/logrus)

          Logrus 是 Go (golang)的結(jié)構(gòu)化 Logger,完全兼容標(biāo)準(zhǔn)庫 Log。

          例子:

          package main

          import (
            log "github.com/sirupsen/logrus"
          )

          func main() {
            log.WithFields(log.Fields{
              "animal""walrus",
            }).Info("A walrus appears")
          }

          項(xiàng)目地址:https://github.com/sirupsen/logrus。

          07、Mock 生成器 (vektra/mockery)

          一個(gè) Mock 代碼自動生成器

          安裝:

          go get github.com/vektra/mockery/v2/.../

          生成 mock:

          ./bin/mockery --all

          輸出:

          項(xiàng)目地址:https://github.com/vektra/mockery。

          08、Migrate (golang-migrate/migrate)

          用 Go 編寫的數(shù)據(jù)庫遷移工具。作為 CLI[3] 使用或作為[4]導(dǎo)入。

          支持如下數(shù)據(jù)庫:

          • PostgreSQL
          • Redshift
          • Ql
          • Cassandra
          • SQLite (todo #165)
          • SQLCipher
          • MySQL/ MariaDB
          • Neo4j
          • MongoDB
          • CrateDB (todo #170)
          • Shell (todo #171)
          • Google Cloud Spanner
          • CockroachDB
          • ClickHouse
          • Firebird
          • MS SQL Server

          安裝:

          $ go get -u -d github.com/golang-migrate/migrate/cmd/migrate

          創(chuàng)建遷移文件:

          migrate create -ext sql -dir database/migrations -seq create_user

          運(yùn)行升級版本:

          migrate -database "mysql://user:pass@tcp(localhost:3600)/user" -path=database/migrations up

          降版本:

          migrate -database "mysql://user:pass@tcp(localhost:3600)/user" -path=database/migrations down

          項(xiàng)目地址:< https://github.com/golang-migrate/migrate>。

          09、Messaging (NSQ)

          NSQ 拓?fù)洌?/p>

          NSQ 組件:

          1. nsqlookupd (daemon manage topologies / routes)
          2. nsqd (daemon manage receives, queues, and delivers messages)
          3. nsqadmin (default Web UI of nsq)

          基于 docker-compose 示例:(nsqlookupd,nsqd,nsqadmin)

          version: '3'
          services:
          nsqlookupd:
          image: nsqio/nsq
          command: /nsqlookupd
          ports:
          - "4160:4160"
          - "4161:4161"
          nsqd:
          image: nsqio/nsq
          command: /nsqd --lookupd-tcp-address=nsqlookupd:4160
          depends_on:
          - nsqlookupd
          ports:
          - "4150:4150"
          - "4151:4151"
          nsqadmin:
          image: nsqio/nsq
          command: /nsqadmin --lookupd-http-address=nsqlookupd:4161
          depends_on:
          - nsqlookupd
          ports:
          - "4171:4171"

          執(zhí)行:

          To run docker:
          $ docker-compose up -d
          or if use name (docker-compose-nsq.yml):
          $ docker-compose -f docker-compose-nsq.yml up -d
          To check container docker:
          $ docker-compose ps
          To see logs:
          $ docker-compose logs
          To check nsq web ui: (assuming port is 32770)
          $ curl http://127.0.0.1:32770/ping

          Go 代碼目錄:

          Create Folder:
          ├── consume
          │   └── consume.go
          └── publish
              └── publish.go

          consume.go 代碼:

          package main
          import (
              "log"
              "sync"
              "github.com/nsqio/go-nsq"
          )
          func main() {
              wg := &sync.WaitGroup{}
              wg.Add(1)
              decodeConfig := nsq.NewConfig()
              c, err := nsq.NewConsumer("My_NSQ_Topic""My_NSQ_Channel", decodeConfig)
              if err != nil {
                log.Panic("Could not create consumer")
              }
              c.AddHandler(nsq.HandlerFunc(func(message *nsq.Message) error {
                  log.Println("NSQ message received:")
                  log.Println(string(message.Body))
                return nil
              }))
              err = c.ConnectToNSQD("127.0.0.1:4150")
              if err != nil {
                log.Panic("Could not connect")
              }
              log.Println("Awaiting messages from NSQ topic \"My NSQ Topic\"...")
              wg.Wait()
          }

          運(yùn)行 consume.go:

          $ go run consume/consume.go

          publish.go 代碼:

          package main
          import (
              "log"
              "github.com/nsqio/go-nsq"
          )
          func main() {
              config := nsq.NewConfig()
              p, err := nsq.NewProducer("127.0.0.1:4150", config)
              if err != nil {
                log.Panic(err)
              }
              err = p.Publish("My_NSQ_Topic", []byte("sample NSQ message"))
              if err != nil {
                log.Panic(err)
              }
          }

          運(yùn)行 publish:

          $ go run publish/publish.go

          項(xiàng)目地址:https://github.com/nsqio/go-nsq。

          10、SQL (jmoiron/sqlx)

          sqlx 是一個(gè)庫,它為 go 的標(biāo)準(zhǔn) database/sql 庫提供了一組擴(kuò)展。

          我喜歡的 sqlx 是因?yàn)樗鼈兛梢?scan 結(jié)構(gòu)!使用簡單。

          StrucScan 的例子:

          place := Place{}
          rows, err := db.Queryx("SELECT * FROM place")
          for rows.Next() {
              err := rows.StructScan(&place)
              if err != nil {
                 log.Fatalln(err)
              } 
              fmt.Printf("%#v\n", place)
          }

          項(xiàng)目地址:https://github.com/jmoiron/sqlx。

          11、附加的一些庫

          1)Go routine grouping (sync/errgroup):https://pkg.go.dev/golang.org/x/sync/errgroup

          2)Fluent SQL generation for golang (Masterminds/squirrel):https://github.com/Masterminds/squirrel

          3)Golang Linter (golangci/golangci-lint):https://github.com/golangci/golangci-lint

          4)Circuit Breaker (gojek/heimdall):https://github.com/gojek/heimdall

          5)Go tool generate tags (fatih/gomodifytags):https://github.com/fatih/gomodifytags

          12、總結(jié)

          要構(gòu)建應(yīng)用程序,我們應(yīng)該知道有什么功能,特別是如果我們是團(tuán)隊(duì)協(xié)作,建議使用可讀性強(qiáng)的代碼,這樣在成為遺留代碼之前(也許 5-10 年之后) ,代碼可以更容易維護(hù)。

          構(gòu)建應(yīng)用程序的三個(gè)關(guān)鍵:

          1. 簡單設(shè)計(jì)(項(xiàng)目結(jié)構(gòu)和依賴關(guān)系)
          2. Clean Code (可讀性和可維護(hù)性)
          3. Modular(模塊化) (Solid & flexible skeleton)

          為了封裝所有這些庫,我有一個(gè)模板或框架項(xiàng)目,其設(shè)計(jì)簡單,代碼清晰。看看這個(gè):https://github.com/kecci/goscription。

          以上就是我常用的 10 大 Go 框架/庫和一些附加庫。

          我希望你喜歡我的推薦,如果你有其他的推薦,請留言!

          原文鏈接:https://keccikun.medium.com/top-10-framework-golang-library-to-build-microservice-391a2bb4c2cb

          作者:Kecci Kun

          編譯:polarisxu

          參考資料

          [1]

          Go Webb 框架: https://github.com/swaggo/swag#supported-web-frameworks

          [2]

          OpenAPI 2.0: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md

          [3]

          CLI: https://github.com/golang-migrate/migrate#cli-usage

          [4]

          庫: https://github.com/golang-migrate/migrate#use-in-your-go-project



          推薦閱讀


          福利

          我為大家整理了一份從入門到進(jìn)階的Go學(xué)習(xí)資料禮包,包含學(xué)習(xí)建議:入門看什么,進(jìn)階看什么。關(guān)注公眾號 「polarisxu」,回復(fù) ebook 獲取;還可以回復(fù)「進(jìn)群」,和數(shù)萬 Gopher 交流學(xué)習(xí)。

          瀏覽 42
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  肏屄视频在线观看 | 亚洲黄色视频在线 | 五月天亚洲综合小说网 | 丁香五月激情小说 | 久久国产乱子伦精品一区二区 |