首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang服务/daos实现

Golang服务/daos实现
EN

Stack Overflow用户
提问于 2016-09-25 17:45:13
回答 1查看 2K关注 0票数 3

我来自Java背景,我有一些关于如何在Golang做事情的问题。我专门讨论的是服务和dao/存储库。

在java中,我将使用依赖项注入(可能是单例/应用程序-作用域),并将服务注入到rest端点/资源中。

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

代码语言:javascript
复制
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是分开的,因为google .

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

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

我应该在每次触发处理程序时这样做,还是使它成为常量/全局的?

为了完整起见,下面是处理程序和blogService:

代码语言:javascript
复制
// 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?
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-26 02:21:06

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

代码语言:javascript
复制
container := request.Context.Value("container").(*Container)
blogs,err := container.GetBlogService().ListBlogs()

阅读以下材料:

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39689881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档