douyinzha5820 2016-09-25 17:45
浏览 231
已采纳

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?
}
  • 写回答

1条回答 默认 最新

  • dongyan5641 2016-09-26 02:21
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭