Golang服务/ dao实施

Coming from a Java background, I have some questions on how things are typically done in Golang. I am specifically talking about services and dao's/repositories.

In java, I would use dependency injection (probably as singleton/application-scoped), and have a Service injected into my rest endpoint / resource.

To give a bit more context. Imagine the following Golang code:

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

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

Copied this directly from my code, main and init are split because google app engine.

So for now I have one handler. In that handler, I expect to interact with a BlogService.

The question is, where, and in what scope should I instantiate a BlogService struct and a dao like datastructure?

Should I do it everytime the handler is triggered, or make it constant/global?

For completeness, here is the handler and 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?
}

You can use context.Context to pass request scoped values into your handlers (available in Go 1.7) , if you build all your required dependencies during the request/response cycle (which you should to avoid race conditions, except for dependencies that manage concurrency on their own like sql.DB). Put all your services into a single container for instance, then query the context for that value :

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

read the following material :

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

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