Golang service/daos 实现

Golang service/daos implementation

来自 Java 背景,我对 Golang 中通常如何完成事情有一些疑问。我具体说的是服务和dao's/repositories.

在 java 中,我会使用依赖注入(可能是 singleton/application-scoped),并将服务注入到我的其余端点/资源中。

提供更多背景信息。想象一下下面的 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 app engine。

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

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

我应该在每次触发处理程序时都这样做,还是让它成为 constant/global?

为了完整起见,这里是处理程序和 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?
}

如果您在 request/response 周期(您应该避免竞争条件,除了像 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