首頁 > 後端開發 > Golang > 主體

微服務的終極 Golang 框架:GoFr

王林
發布: 2024-07-17 07:58:38
原創
746 人瀏覽過

GoFr: The Ultimate Golang Framework for Microservices

Go 是由 Google 設計的多典範、靜態型別和編譯式程式語言。許多開發人員之所以接受 Go,是因為它的垃圾收集、記憶體安全和結構類型系統。 Go Web 框架的創建是為了簡化 Go Web 開發過程,而無需擔心設定並更專注於專案的功能。在建立小型應用程式時,框架可能不是必需的,但對於生產級軟體來說,它們至關重要。框架提供了額外的功能和服務,可供其他想要向其軟體添加類似功能而不是自己編寫成熟軟體的開發人員使用。

根據您的需求選擇正確的框架可以加快開發週期並更輕鬆地進行維護。在本文中,我們將討論 GoFr,一個用於加速微服務開發的固執己見的 Golang 框架。我們將發現為什麼它是您在 Go 中建立微服務時的最終選擇!


GoFr 具有豐富的功能:

真正決定框架好壞的是它為用戶提供的開發簡易性以及它提供的一系列功能,以便用戶可以完全專注於業務邏輯實現。 GoFr 旨在幫助開發人員編寫快速、可擴展且高效的 API。該框架提供了一組豐富的功能,可協助開發人員輕鬆編寫生產級微服務。讓我們來探索其中一些功能:

1. 高效率的組態管理

環境變數是為軟體應用程式設定配置值的最佳方式,因為它們可以在系統層級定義,獨立於軟體。這是十二要素應用程式方法論的原則之一,使應用程式能夠以可移植性的方式建構。

GoFr 有一些預先定義的環境變數用於各種目的,例如更改日誌等級、連接到資料庫、設定應用程式名稱和版本、設定 http 連接埠等。使用者只需在 configs 目錄內的 .env 檔案中設定這些變數應用程式和 GoFr 自動從中讀取值。

這是 GoFr 支援的環境變數的完整列表

2. 無縫資料庫交互

管理資料庫連線和互動可能會變得忙碌,尤其是在使用多個資料庫時。 GoFr 使用設定變數無縫處理資料庫連線。它不僅管理連接,而且還使用處理程序中的 GoFr 上下文提供對資料庫物件的直接存取。這種方法簡化了多個資料庫的使用。 GoFr 目前支援所有 SQL Dialects、Redis、MongoDB、Cassandra 和 ClickHouse 資料庫。

在處理程序中使用 MySQL 和 Redis DB 的範例。

func DBHandler(c *gofr.Context) (interface{}, error) {
 var value int

// querying a SQL db
err := c.SQL.QueryRowContext(c, "select 2+2").Scan(&value)
 if err != nil {
  return nil, datasource.ErrorDB{Err: err, Message: "error from sql db"}
 }

// retrieving value from Redis
 _, err = c.Redis.Get(c, "test").Result()
 if err != nil && !errors.Is(err, redis.Nil) {
  return nil, datasource.ErrorDB{Err: err, Message: "error from redis db"}
 }

 return value, nil
}
登入後複製

3. 輕鬆實施發布者-訂閱者架構:

GoFr 透過為 Kafka、Google Pub/Sub 和 MQTT 等流行客戶端提供內建支援,簡化了 Pub/Sub。這消除了手動配置或庫管理的需要,使您可以專注於事件驅動的架構。使用 GoFr 上下文簡化了事件的發布和訂閱。可以使用上下文在處理程序內部完成事件發布,並且要訂閱事件,您只需要使用 GoFr 的訂閱處理程序。與從頭開始實作 Pub/Sub 模式相比,這種方法可以促進乾淨的程式碼並減少樣板程式碼。

在 GoFr 應用程式中使用發布者和訂閱者的範例:

package main

import (
 "encoding/json"

 "gofr.dev/pkg/gofr"
)

func main() {
 app := gofr.New()

 app.POST("/publish-product", product)

// subscribing to products topic
 app.Subscribe("products", func(c *gofr.Context) error {
  var productInfo struct {
   ProductId string `json:"productId"`
   Price     string `json:"price"`
  }

  err := c.Bind(&productInfo)
  if err != nil {
   c.Logger.Error(err)

   return nil
  }

  c.Logger.Info("Received product ", productInfo)

  return nil
 })

 app.Run()
}

func product(ctx *gofr.Context) (interface{}, error) {
 type productInfo struct {
  ProductId string `json:"productId"`
  Price     string `json:"price"`
 }

 var data productInfo

// binding the request data to productInfo struct
 err := ctx.Bind(&data)
 if err != nil {
  return nil, err
 }

 msg, _ := json.Marshal(data)

// publishing message to producst topic using gofr context
 err = ctx.GetPublisher().Publish(ctx, "products", msg)
 if err != nil {
  return nil, err
 }

 return "Published", nil
}
登入後複製

4.開箱即用的可觀察性:

有效的監控對於維持高效能的微服務至關重要。 GoFr 透過提供內建的可觀察性功能減輕您肩上的負擔。這消除了手動配置追蹤、指標和日誌記錄庫的需要。

  • 詳細日誌記錄:GoFr 提供具有各種日誌等級(INFO、DEBUG、WARN、ERROR、FATAL)的結構化日誌記錄,以捕獲不同粒度的應用程式事件。這使您能夠分析應用程式流程、識別潛在問題並簡化偵錯。

  • 可操作指標: GoFr 自動收集和公開應用程式指標,讓您能夠監控關鍵效能指標。透過隨時可用的指標,您可以快速識別瓶頸並優化應用程式效能。

  • Distributed Tracing: GoFr integrates with popular tracing backends like Zipkin and Jaeger. Distributed tracing allows you to visualize the entire request lifecycle across your microservices, making it easier to pinpoint the root cause of issues within complex systems.

These observability features help users gain detailed insights into the application's flow and performance, identify and resolve bottlenecks, and ensure smooth operation.

5. Effortless Interservice HTTP Communication:

In a microservices architecture, efficient and reliable communication between services is crucial. GoFr simplifies this process by providing a dedicated mechanism to initialize and manage interservice HTTP communication. You can easily register downstream services at the application level using the AddHTTPService method.

Configurational Options for HTTP Services:

GoFr offers a variety of configuration options to enhance interservice communication:

  • Authentication: Supports APIKeyConfig, BasicAuthConfig, and OAuthConfig for secure authentication.

  • Default Headers: Allows setting default headers for all downstream HTTP service requests.

  • Circuit Breaker: Enhance service resilience with built-in circuit breaker functionality. GoFr allows you to configure thresholds and intervals to gracefully handle failures and prevent cascading outages.

  • Health Checks: Proactively monitor the health of your downstream services using GoFr's health check configuration. Define a health endpoint for each service, and GoFr will automatically verify their availability, allowing for early detection of potential issues.

These features ensure that interservice communication is secure, reliable, and easily manageable.

Example of connecting to a HTTP Service and sending a GET request:

func main() {
 a := gofr.New()

 a.AddHTTPService("cat-facts", "https://catfact.ninja",
  &service.CircuitBreakerConfig{
   Threshold: 4,
   Interval:  1 * time.Second,
  },
  &service.HealthConfig{
   HealthEndpoint: "breeds",
  },
 )

a.GET("/fact", Handler)

 a.Run()
}

func Handler(c *gofr.Context) (any, error) {
 var data = struct {
  Fact   string `json:"fact"`
  Length int    `json:"length"`
 }{}

 var catFacts = c.GetHTTPService("cat-facts")

 resp, err := catFacts.Get(c, "fact", map[string]interface{}{
  "max_length": 20,
 })
 if err != nil {
  return nil, err
 }

 b, _ := io.ReadAll(resp.Body)
 err = json.Unmarshal(b, &data)
 if err != nil {
  return nil, err
 }

 return data, nil
}
登入後複製

6. Flexible Middleware Support for Enhanced Control:

Middleware allows you intercepting and manipulating HTTP requests and responses flowing through your application's router. Middlewares can perform tasks such as authentication, authorization, caching etc. before or after the request reaches your application's handler.

GoFr empowers developers with middleware support, allowing for request/response manipulation and custom logic injection. This provides a powerful mechanism to implement cross-cutting concerns like authentication, authorization, and caching in a modular and reusable way. Middleware functions are registered using the UseMiddleware method on your GoFr application instance.

Additionally, GoFr includes built-in CORS (Cross-Origin Resource Sharing) middleware to handle CORS-related headers.

Example of adding a custom middleware to GoFr application:

import (
    "net/http"

    gofrHTTP "gofr.dev/pkg/gofr/http"
)

// Define your custom middleware function
func customMiddleware() gofrHTTP.Middleware {
    return func(inner http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // Your custom logic here
            // For example, logging, authentication, etc.

            // Call the next handler in the chain
            inner.ServeHTTP(w, r)
        })
    }
}

func main() {
    // Create a new instance of your GoFr application
    app := gofr.New()

    // Add your custom middleware to the application
    app.UseMiddleware(customMiddleware())

    // Define your application routes and handlers
    // ...

    // Run your GoFr application
    app.Run()
}
登入後複製

7. Integrated Authentication Mechanisms:

Securing your microservices with robust authentication is crucial. GoFr streamlines this process by providing built-in support for various industry-standard authentication mechanisms. This empowers you to choose the approach that best suits your application's needs without writing complex authentication logic from scratch.

  • Basic Auth: Basic auth is the simplest way to authenticate your APIs. It's built on HTTP protocol authentication scheme. It involves sending the prefix Basic trailed by the Base64-encoded : within the standard Authorization header. GoFr offers two ways to implement basic authentication i.e. using pre-defined credentials as well as defining a custom validation function.

  • API Keys Auth: API Key Authentication is an HTTP authentication scheme where a unique API key is included in the request header for validation against a store of authorized keys. GoFr offers two ways to implement API Keys authentication i.e. Framework Default Validation as well as defining a Custom Validation Function.

  • OAuth 2.0: OAuth 2.0 is the industry-standard protocol for authorization. It focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. It involves sending the prefix Bearer trailed by the encoded token within the standard Authorization header. GoFr supports authenticating tokens encoded by algorithm RS256/384/512.

Refer to the GoFr's Authentication Documentation to see the examples of how to use these auth mechanisms and know more about it.

---

  1. 自動 Swagger UI 渲染:

提供清晰且互動的 API 文件對於使用者採用且有效率的開發工作流程至關重要。 API規格可以用YAML或JSON寫。該格式對於人類和機器來說都很容易學習和閱讀。完整的 OpenAPI 規範可以在 Swagger 官方網站上找到。

GoFr 支援 OpenAPI(也稱為 Swagger)文件的自動渲染。此功能可讓您輕鬆為使用者提供互動式 API 文件。要允許 GoFr 呈現您的 OpenAPI 文檔,只需將 openapi.json 文件放入專案的靜態目錄中即可。 GoFr 會在 /.wellknown/swagger 端點自動渲染 Swagger 文件。


結論

在本文中,我們探索了 GoFr 的豐富功能,GoFr 是一個專為加速微服務開發而設計的固執己見的 Golang 框架。我們已經了解了 GoFr 如何簡化配置管理、資料庫互動、Pub/Sub 整合、自動可觀察性、服務間通訊、中間件使用和身份驗證等常見任務。此外,GoFr 還提供對資料遷移、Web 套接字、cron 作業和遠端日誌層級變更的內建支持,進一步簡化您的開發流程。

我們將 GoFr 與其他流行的 Go 框架(如 Gin、Chi、Echo 和 Fiber)進行了基準測試,發現 GoFr 的性能最佳,即使具有廣泛的功能集。這意味著您可以在不影響效能的情況下利用其所有強大的功能。

我們鼓勵您親自探索 GoFr。該框架的綜合文件、教程和活躍的社區是指導您的旅程的寶貴資源。透過 GoFr,您可以專注於建立健壯、可擴展且高效管理的微服務,從而將更多時間投入到應用程式的核心功能上。

立即開始使用 GoFr!

這裡有一些有用的資源:

GoFr 網址:https://gofr.dev
GoFr GitHub 儲存庫:https://github.com/gofr-dev/gofr
GoFr Discord 伺服器:https://discord.gg/zyJkVhps

以上是微服務的終極 Golang 框架:GoFr的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!