2016-07-14 121 views
1

我想我使用gorm ORM库和gin框架Golang抽象,以避免重复代码

基类

type Base struct { 
    Context *gin.Context // Passing gin request 
} 

func (b *Base) Add() { 
    err := b.Context.BindJSON(b) 
    if err != nil { 
    // handling error here 
    } 
    gorm.db.Create(b) // Here I am adding base data to database 
} 

子类来实现golang 抽象

type Shopper struct { 
    Base // Embedding Base struct 
    Name string, 
    Address string, 
    ContactNo int 
} 

处理程序

func handler (c *gin.Context) { 
    s := new(Shopper) 
    s.Context = c 
    s.Add() // Here I am expecting Add() method should bind JSON to shopper struct 
      // entry to database using gorm 
} 

Add()方法没有采取其shopper结构有任何属性。

在这里,我只是想避免在每个handler其中 只是需要从JSON请求主体code duplication和使用gorm

回答

2

你不能因为Go does not have inheritance添加到相应的database

让我再说一遍:Go没有继承,所以请在与Go一起工作时忘记这个“基础”和“孩子”的东西。

您的代码不工作的原因是,虽然中 方法组嵌入型确实是“解禁”并合并到方法设置中嵌入它的类型, 当任何这样的方法被称为 它的接收器是嵌入式类型的值而不是 值。

督察您Add()方法总是收到类型Base

的值如果封闭类型具有同名 作为嵌入式类型的方法的方法,并调用该方法 上的一个值封闭类型,封装 类型的方法将被调用。 所以没有超载,但如果你愿意的话,有“重载”。

我会在你的情况是停在OOP 想做些什么,并写了一个函数,而不是(未经测试)的方法:

func add(any interface{}, ctx *gin.Context) { 
    err := ctx.BindJSON(any) 
    if err != nil { 
    // handling error here 
    } 
    gorm.db.Create(any) // Here I am adding base data to database 
} 

然后在您的处理程序:

func handler (c *gin.Context) { 
    s := new(Shopper) 
    s.Context = c 
    add(s, c) 
} 
+0

谢谢kostix –