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
謝謝kostix –