gpt4 book ai didi

go - Golang 中的工厂函数

转载 作者:IT王子 更新时间:2023-10-29 01:40:50 25 4
gpt4 key购买 nike

<分区>

我有一个类似于下面显示的服务对象,它通过 HTTP 公开:

type ComputeService struct {

}

func (svc ComputeService) Compute(userType string, data Data) (Result, error) {
// rate limit based on userType (both check and increment counter)
// if not rate limited, compute and return result
}

现在,正如您所看到的,需要根据 userType 完成速率限制。速率限制器本身的实现根据 userType 发生变化。我正在考虑使用 userType 解决速率限制器的两种方法。

// First approach: for each request new ComputeService object is
// created after resolving RateLimiter using userType in the handler
// itself
type ComputeService struct {
RateLimiter RateLimiter
}

// Second approach: ComputeService object is initialized during startup
// and only RateLimiter is resolved with every Compute() call by calling
// the provider function
type ComputeService struct {
RateLimiterProvider func(userType string) RateLimiter
}

两者都是可测试的。哪一个更可取?我倾向于第二种方法,因为使用它意味着处理程序将纯粹是读取请求、委托(delegate)服务、写出响应,而在第一种方法中,处理程序将包含解决速率限制器实现的额外步骤。

25 4 0
文章推荐: go - 有没有办法在不使用自定义结构的情况下检索实体?
文章推荐: xml - 如何在 Inno Setup 中读写 XML 文档节点值?
文章推荐: xml - cvc-complex-type.2.4.a : invalid content was found starting with element 'ProcessDesc' . ProcessName 预期之一
文章推荐: html - 如何在 Golang 中设置 HTML