Where to get the Context for DB query?

huangapple go评论68阅读模式
英文:

Where to get the Context for DB query?

问题

我正在使用https://entgo.io/作为实体框架,https://echo.labstack.com/作为Web框架。

考虑以下代码片段:

func main() {

	client, err := Open("postgresql://pgadmin:pgpw@127.0.0.1/nfeed")
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	ctx := context.Background()

	if err := client.Schema.Create(ctx); err != nil {
		log.Fatal(err)
		return
	}


	e := echo.New()


	e.GET("/hashtags", func(c echo.Context) error {
		pattern := c.QueryParam("pattern")
		if len(pattern) == 0 {
			return c.JSON(http.StatusNotFound, err)
		}

		hs, err := client.Hashtag.Query().All(????)


		return c.JSON(http.StatusOK, "Hello")
	})
	e.Logger.Fatal(e.Start(":3000"))
}

函数调用client.Hashtag.Query().All(context)期望的参数是https://pkg.go.dev/context。

问题是,我应该如何获取或者在哪里获取这个context?
在我看来,Echo框架应该提供给我一个Context。不幸的是,在Echo模块中我找不到它。

英文:

I am using https://entgo.io/ as entity framework and https://echo.labstack.com/ as web framework.

Consider the following code snippet:


func main() {

	client, err := Open("postgresql://pgadmin:pgpw@127.0.0.1/nfeed")
	if err != nil {
		log.Fatal(err.Error())
		return
	}
	ctx := context.Background()

	if err := client.Schema.Create(ctx); err != nil {
		log.Fatal(err)
		return
	}


	e := echo.New()


	e.GET("/hashtags", func(c echo.Context) error {
		pattern := c.QueryParam("pattern")
		if len(pattern) == 0 {
			return c.JSON(http.StatusNotFound, err)
		}

		hs, err := client.Hashtag.Query().All(????)


		return c.JSON(http.StatusOK, "Hello")
	})
	e.Logger.Fatal(e.Start(":3000"))
}

The function call client.Hashtag.Query().All(context) expects https://pkg.go.dev/context as parameter.

The question is, how or where can I get the context?
In my opinion, the Echo framework should provide me a Context. Unfortunately, I could not found within the Echo module.

答案1

得分: 2

你在第ctx := context.Background()行定义了一个上下文变量,它是一个有效的context类型,在你提供的链接https://pkg.go.dev/context中有很好的文档。

没有理由它不能工作,如果你需要更多信息,可以查看文档,了解如何创建更详细的上下文变量。

英文:

You define a context variable on the line ctx := context.Background(), which is a valid context type, there's good documentation on this in your own link https://pkg.go.dev/context.

There's no reason that wouldn't work, if you need more then you can check the documentation on how to make a more in depth context variable.

huangapple
  • 本文由 发表于 2021年8月20日 20:09:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/68862026.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定