douguang9014 2017-02-27 06:26
浏览 161
已采纳

我们可以将额外的参数传递给beego路由器吗

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条回答 默认 最新

  • dtkl55257 2017-02-27 10:20
    关注

    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

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

报告相同问题?