英文:
can we pass extra parameter to a beego router
问题
你好,以下是翻译好的内容:
type MainController struct {
beego.Controller
}
func (this *MainController) Post() {
var datapoint User
req := this.Ctx.Input.RequestBody
json.Unmarshal([]byte(req), &datapoint)
this.Ctx.WriteString("hello world")
// result := this.Input()
fmt.Println("input value is", datapoint.UserId)
}
这是一个正常的beego路由器,它在URL出现时执行。我想要像下面这样的东西:
type MainController struct {
beego.Controller
}
func (this *MainController, db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
以便使用数据库连接指针。请问在Go语言中是否可以实现这个?如果不行,请给予建议。
英文:
type MainController struct {
beego.Controller
}
func (this *MainController) Post() {
var datapoint User
req := this.Ctx.Input.RequestBody
json.Unmarshal([]byte(req), &datapoint)
this.Ctx.WriteString("hello world")
// result := this.Input()
fmt.Println("input value is", datapoint.UserId)
}
this is normal beego router which executes on url occurrence. I want something like
type MainController struct {
beego.Controller
}
func (this *MainController,db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
in order to use database connection pointer. is this possible to achieve this using go...if not please suggest
答案1
得分: 0
你不能在golang中这样做。
type MainController struct {
beego.Controller
}
func (this *MainController, db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
在这个形式的声明中,
function (c *MainController)Post()
意味着Post
是MainController
结构体的一个方法,你可以将变量传递给它。
我的建议是你在包中将db
指针声明为全局变量,如下所示,然后你就可以在Post
函数内部使用它了。
type MainController struct {
beego.Controller
}
var db *sql.DB
func (this *MainController) Post() {
// 现在你可以在这里使用变量db了
fmt.Println("input value is", datapoint.UserId)
}
但考虑到这是使用MVC模式的Beego框架,你可以在模型中完成所有这些操作。我建议你查看他们很棒的文档。
英文:
You can't do this in golang
type MainController struct {
beego.Controller }
func (this *MainController,db *sql.DB) Post() {
fmt.Println("input value is", datapoint.UserId)
}
the declaration in the form
function (c *MainController)Post()
means that Post is a method for the MainController
struct you can pass variable into it.
My suggestion is you declare the db pointer as a global variable in your package like below then you will be able to use it inside the Post
function
type MainController struct {
beego.Controller
}
var db *sql.DB
func (this *MainController) Post() {
//you can now use the variable db inside here
fmt.Println("input value is", datapoint.UserId)
}
but considering this is Beego which uses the MVC pattern you can do all this from within the model. I suggest you take a look at their awesome documentation here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论