我来自Java背景,我有一些关于如何在Golang做事情的问题。我专门讨论的是服务和dao/存储库。
在java中,我将使用依赖项注入(可能是单例/应用程序-作用域),并将服务注入到rest端点/资源中。
提供更多的背景信息。想象一下以下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是分开的,因为google .
所以现在我有一个处理程序。在该处理程序中,我希望与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?
}发布于 2016-09-26 02:21:06
如果在请求/响应周期中构建所有所需的依赖项(除了管理并发性的依赖项(如context.Context )之外,您应该避免竞争条件,则可以使用sql.DB将请求范围内的值传递给处理程序(在Go 1.7中可用)。例如,将所有服务放入一个容器中,然后查询上下文中的值:
container := request.Context.Value("container").(*Container)
blogs,err := container.GetBlogService().ListBlogs()阅读以下材料:
https://stackoverflow.com/questions/39689881
复制相似问题