2016-07-14 202 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 –