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

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

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面