Search code examples
gobeego

How to remove duplicate ORM instantiation in Golang Beego


In Golang application model

I have below:

func AddClub(name string) int64 {
    o := orm.NewOrm()
    club := Club{Name: name}

    id, err := o.Insert(&club)
    if err != nil {
        fmt.Printf("Id: %s, Error: %s", id, err)
    }

    return id
}

Then below:

func GetAllClubs() []*Club {
    o := orm.NewOrm()

    var clubs []*Club
    num, err := o.QueryTable("clubs").All(&clubs)
    if err != nil {
        fmt.Printf("Returned Rows Num: %s, %s", num, err)
    }
    return clubs
}

I want to remove duplication of o := orm.NewOrm() instantiation. How do I do this?

I tried to put it as part of init() func like below:

func init() {
  o := orm.NewOrm()
}

But I get undefined o error in console


Solution

  • If you want to define a variable that is available for the entire package .. you need to declare it at the package level (if you're not going to be injecting it). That is, outside of any functions.

    You also cannot use the shorthand := initialization for this - it must be explicit.

    Therefore it must be something like:

    var o orm.Ormer
    
    func init() {
        o = orm.NewOrm()
    }
    

    Notice that it is declared outside of the function, and it doesn't use the shorthand initialization and assignment operator :=.