gpt4 book ai didi

Golang 服务/daos 实现

转载 作者:IT王子 更新时间:2023-10-29 01:09:35 30 4
gpt4 key购买 nike

我有 Java 背景,我对 Golang 中通常如何完成事情有一些疑问。我专门谈论服务和 dao 的/存储库。

在 java 中,我会使用依赖注入(inject)(可能是单例/应用程序范围),并将服务注入(inject)到我的其余端点/资源中。

提供更多背景信息。想象一下下面的 Golang 代码:

func main() {
http.ListenAndServe("localhost:8080", nil)
}

func init() {
r := httptreemux.New()
api := r.NewGroup("/api/v1")
api.GET("/blogs", GetAllBlogs)
http.Handle("/", r)
}

直接从我的代码中复制了这个,main 和 init 是分开的,因为谷歌应用引擎。

所以现在我只有一个处理程序。在该处理程序中,我希望与 BlogService 交互。

问题是,我应该在哪里以及在什么范围内实例化 BlogService 结构和类似 dao 的数据结构?

我应该在每次触发处理程序时都执行此操作,还是将其设为常量/全局?

为了完整起见,这里是处理程序和 blogService:

// GetAllBlogs Retrieves all blogs from GCloud datastore
func GetAllBlogs(w http.ResponseWriter, req *http.Request, params map[string]string) {
c := appengine.NewContext(req)
// need a reference to Blog Service at this point, where to instantiate?
}

type blogService struct{}

// Blog contains the content and meta data for a blog post.
type Blog struct {...}

// newBlogService constructs a new service to operate on Blogs.
func newBlogService() *blogService {
return &blogService{}
}

func (s *blogService) ListBlogs(ctx context.Context) ([]*Blog, error) {
// Do some dao-ey / repository things, where to instantiate BlogDao?
}

最佳答案

您可以使用 context.Context 将请求范围内的值传递给您的处理程序(在 Go 1.7 中可用),如果您在请求/响应周期中构建所有必需的依赖项(您应该避免这种情况竞争条件,除了自行管理并发的依赖项,如 sql.DB)。例如,将所有服务放入一个容器中,然后查询该值的上下文:

container := request.Context.Value("container").(*Container)
blogs,err := container.GetBlogService().ListBlogs()

阅读以下 Material :

https://golang.org/pkg/context/

https://golang.org/pkg/net/http/#Request.Context

关于Golang 服务/daos 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39689881/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com