ホームページ  >  記事  >  バックエンド開発  >  マイクロサービス向けの究極の Golang フレームワーク: GoFr

マイクロサービス向けの究極の Golang フレームワーク: GoFr

王林
王林オリジナル
2024-07-17 07:58:38747ブラウズ

GoFr: The Ultimate Golang Framework for Microservices

Go は、Google によって設計されたマルチパラダイムの、静的に型付けされ、コンパイルされたプログラミング言語です。多くの開発者は、ガベージ コレクション、メモリの安全性、構造的な型付けシステムのおかげで Go を採用してきました。 Go Web フレームワークは、セットアップを気にせず、プロジェクトの機能に重点を置くことなく、Go Web 開発プロセスを容易にするために作成されました。小規模なアプリケーションを構築する場合、フレームワークは必要ないかもしれませんが、実稼働レベルのソフトウェアの場合、フレームワークは非常に重要です。フレームワークは、本格的なソフトウェアを自分で作成するのではなく、同様の機能をソフトウェアに追加したい他の開発者が使用できる追加の機能とサービスを提供します。

ニーズに適したフレームワークを選択すると、開発サイクルが短縮され、将来のメンテナンスが容易になります。この記事では、マイクロサービス開発を加速するための独自の Golang フレームワークである GoFr について説明します。そして、なぜそれが Go でマイクロサービスを構築する際の究極の選択であるのかを説明します!


GoFr とその豊富な機能セット:

フレームワークの良し悪しを決めるのは、フレームワークがユーザーに提供する開発の容易さと、ユーザーがビジネス ロジックの実装に純粋に集中できるようにする幅広い機能です。 GoFr は、開発者が高速でスケーラブルで効率的な API を作成できるように構築されています。このフレームワークは、開発者が運用グレードのマイクロサービスを簡単に作成できるようにする豊富な機能セットを提供します。これらの機能のいくつかを見てみましょう:

1. 効率的な構成管理

環境変数は、ソフトウェアとは独立してシステムレベルで定義できるため、ソフトウェアアプリケーションの構成値を設定する最良の方法です。これは、Twelve-Factor App 手法の原則の 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 の Subscribe ハンドラーを使用するだけです。このアプローチは、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 の公式 Web サイトでご覧いただけます。

GoFr は、OpenAPI (Swagger とも呼ばれます) ドキュメントの自動レンダリングをサポートしています。この機能を使用すると、ユーザーにインタラクティブな API ドキュメントを簡単に提供できます。 GoFr が OpenAPI ドキュメントをレンダリングできるようにするには、openapi.json ファイルをプロジェクトの静的ディレクトリ内に配置するだけです。 GoFr は、/.well-known/swagger エンドポイントで Swagger ドキュメントを自動的にレンダリングします。


結論

この記事では、マイクロサービス開発を加速するために特別に設計された独自の Golang フレームワークである GoFr の豊富な機能を検討してきました。 GoFr が構成管理、データベース操作、Pub/Sub 統合、自動オブザーバビリティ、サービス間通信、ミドルウェアの使用、認証などの一般的なタスクをどのように簡素化するかを見てきました。さらに、GoFr はデータ移行、Web ソケット、cron ジョブ、リモート ログ レベルの変更のサポートを組み込み、開発プロセスをさらに合理化します。

Gin、Chi、Echo、Fiber などの他の一般的な Go フレームワークに対して GoFr をベンチマークしたところ、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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。