>  기사  >  백엔드 개발  >  마이크로서비스를 위한 최고의 Golang 프레임워크: GoFr

마이크로서비스를 위한 최고의 Golang 프레임워크: GoFr

王林
王林원래의
2024-07-17 07:58:38748검색

GoFr: The Ultimate Golang Framework for Microservices

Go는 Google이 설계한 다중 패러다임, 정적으로 유형 지정 및 컴파일된 프로그래밍 언어입니다. 많은 개발자들이 Go의 가비지 수집, 메모리 안전성, 구조적 타이핑 시스템 때문에 Go를 채택했습니다. Go 웹 프레임워크는 설정에 대해 걱정하지 않고 프로젝트 기능에 더 집중하지 않고도 Go 웹 개발 프로세스를 쉽게 하기 위해 만들어졌습니다. 소규모 애플리케이션을 구축하는 동안 프레임워크는 필요하지 않을 수 있지만 프로덕션 수준 소프트웨어의 경우 프레임워크는 매우 중요합니다. 프레임워크는 완전한 소프트웨어를 직접 작성하는 대신 자신의 소프트웨어에 유사한 기능을 추가하려는 다른 개발자가 사용할 수 있는 추가 기능과 서비스를 제공합니다.

귀하의 요구 사항에 맞는 올바른 프레임워크를 선택하면 개발 주기가 빨라지고 향후 유지 관리가 쉬워질 수 있습니다. 이 기사에서는 가속화된 마이크로서비스 개발을 위한 독창적인 Golang 프레임워크인 GoFr에 대해 설명합니다. 그리고 Go에서 마이크로서비스를 구축할 때 이것이 왜 최고의 선택인지 알아보겠습니다!


GoFr & It의 풍부한 기능 세트:

프레임워크를 실제로 좋게 또는 나쁘게 만드는 것은 사용자가 비즈니스 로직 구현에만 집중할 수 있도록 제공하는 다양한 기능과 함께 사용자에게 제공하는 개발 용이성입니다. GoFr은 개발자가 빠르고 확장 가능하며 효율적인 API를 작성할 수 있도록 제작되었습니다. 프레임워크는 개발자가 프로덕션 수준의 마이크로서비스를 쉽게 작성하는 데 도움이 되는 풍부한 기능 세트를 제공합니다. 다음 기능 중 일부를 살펴보겠습니다.

1. 효율적인 구성 관리

환경 변수는 소프트웨어와 관계없이 시스템 수준에서 정의할 수 있으므로 소프트웨어 애플리케이션의 구성 값을 설정하는 가장 좋은 방법입니다. 이는 Twelve-Factor App 방법론의 원칙 중 하나이며 이식성을 갖춘 애플리케이션 구축을 가능하게 합니다.

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 파일을 프로젝트의 static 디렉터리에 넣기만 하면 됩니다. GoFr은 /.well-known/swagger 엔드포인트에서 Swagger 문서를 자동으로 렌더링합니다.


결론

이 기사 전체에서 우리는 마이크로서비스 개발을 가속화하기 위해 특별히 설계된 독창적인 Golang 프레임워크인 GoFr의 풍부한 기능을 살펴보았습니다. 우리는 GoFr이 구성 관리, 데이터베이스 상호 작용, Pub/Sub 통합, 자동 관찰 가능성, 서비스 간 통신, 미들웨어 사용 및 인증과 같은 일반적인 작업을 어떻게 단순화하는지 살펴보았습니다. 또한 GoFr은 데이터 마이그레이션, 웹 소켓, 크론 작업 및 원격 로그 수준 변경에 대한 기본 지원을 제공하여 개발 프로세스를 더욱 간소화합니다.

Gin, Chi, Echo, Fiber 등 다른 인기 있는 Go 프레임워크와 비교하여 GoFr을 벤치마킹한 결과 GoFr이 광범위한 기능 세트에도 불구하고 최적의 성능을 발휘한다는 사실을 발견했습니다. 이는 성능 저하 없이 모든 강력한 기능을 활용할 수 있음을 의미합니다.

GoFr을 직접 살펴보시기 바랍니다. 프레임워크의 포괄적인 문서, 튜토리얼 및 활발한 커뮤니티는 귀하의 여정을 안내하는 귀중한 리소스입니다. GoFr을 사용하면 강력하고 확장 가능하며 효율적으로 관리되는 마이크로서비스를 구축하는 데 집중할 수 있으므로 애플리케이션의 핵심 기능에 더 많은 시간을 할애할 수 있습니다.

오늘 GoFr을 시작해보세요!

다음은 유용한 리소스입니다.

GoFr 웹사이트: https://gofr.dev
GoFr GitHub 저장소: https://github.com/gofr-dev/gofr
GoFr 디스코드 서버: https://discord.gg/zyJkVhps

위 내용은 마이크로서비스를 위한 최고의 Golang 프레임워크: GoFr의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.