1 回答

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
這很大程度上是通過(guò)使用接口來(lái)實(shí)現(xiàn)的。
假設(shè)您創(chuàng)建一個(gè) Web 應(yīng)用程序并且想要顯示用戶(hù)。
首先,您需要定義一個(gè)接口,例如
type Creator interface{
Create(u User)(User,error)
}
type Reader interface{
Read(k PrimaryKey)(User, error)
ListAll()([]User,error)
ListPaginated(page, offset int)([]User,error)
}
type Updater interface{
Update(u User)(User, error)
UpdateByKey(k PrimaryKey, u User)(User, error)
UpdateMany(...User)error
}
type Deleter interface{
Delete(u User)error
DeleteMany(u ...User)error
DeleteByKey(keys ...PrimaryKey)error
}
type CRUD interface {
Creator
Reader
Updater
Deleter
}
接下來(lái),為您想要支持的每種數(shù)據(jù)庫(kù)類(lèi)型實(shí)現(xiàn) CRUD 接口。
現(xiàn)在,您可以創(chuàng)建一個(gè)處理程序:
// ListHandler uses an interface instead of a concrete type to
// retrieve the data from the databases.
// Not only does this approach make it possible to provide different
// implementations, but it makes unit testing way easier.
//
// "Thou Shalt Write Tests"
func ListHandler(rdr Reader) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Pagination ommited for brevity
// Note that the handler is agnostic of the underlying implementation.
u, err := rdr.ListAll()
if err != nil {
log.Printf("ListHandler: error retrieving user list: %s", err)
// Do not do this in production! It might give an attacker information
// Use a static error message instead!
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(u); err != nil {
log.Printf("ListHandler: error encoding user list to JSON: %s", err)
// See above
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
}
并設(shè)置如下:
func main() {
// Get your config
// Then simply use an implementation of CRUD
var dbConn CRUD
switch cfg.DbType {
case "myql":
// returns your implementation of CRUD using MySQL
dbConn = createMySQLConnector(cfg)
case "oracle":
// returns your implementation of CRUD using Oracle
dbConn = createOracleConnector(cfg)
}
http.Handle("/users/", ListHandler(dbConn))
log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}
哈
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報(bào)