LoginSignup
6
6

More than 5 years have passed since last update.

revelでmgo実装テスト その1

Posted at

 今回は、revelでmgoを使ってDBを利用するための下準備です。まずはDBを制御するためのcontrollerを実装していきます。参考にしたのは以下のサイトです。こちらをもとに少し使いやすくしています。
<参考サイト>
http://denis.papathanasiou.org/2012/10/14/go-golang-and-mongodb-using-mgo/

 sessionをコントロールするので、session.goというcontrollerを作成します。
主な機能は
①session構築(cloneSession)
②Entity挿入(InsertEntity)
③Entityの削除(RemoveEntity)
④Collectionのquery(queryCollection)
⑤検索(Search)

session.go
package controllers

import (
    "labix.org/v2/mgo"
)

var (
    session *mgo.Session
    err     error
)

// new session create
func cloneSession(dialURL string) *mgo.Session {
    if session == nil {
        session, err = mgo.Dial(dialURL)
        if err != nil {
            panic(err) //no, not really
        }
    }
    return session.Clone()
}

// insertEntity
func InsertEntity(dbName string,
    collection string,
    dialURL string,
    model interface{}) {

    session := cloneSession(dialURL)
    defer session.Close()

    err := session.DB(dbName).C(collection).Insert(model)
    if err != nil {
        panic(err)
    }
}

// removeEntity
func RemoveEntity(dbName string,
    collection string,
    dialURL string,
    model interface{}) {

    session := cloneSession(dialURL)
    defer session.Close()

    err := session.DB(dbName).C(collection).Remove(model)
    //err := session.DB(dbName).C(collection).RemoveAll(model)

    if err != nil {
        panic(err)
    }
}

// Query collection
func queryCollection(dbName string,
    collection string,
    dialURL string,
    query func(c *mgo.Collection) error) error {

    session := cloneSession(dialURL)
    defer session.Close()

    c := session.DB(dbName).C(collection)

    return query(c)
}

// Search
func Search(q interface{},
    skip int,
    limit int,
    dbName string,
    collection string,
    dialURL string) (results []interface{}, errorCode string) {

    errorCode = ""
    query := func(c *mgo.Collection) error {
        fn := c.Find(q).Skip(skip).Limit(limit).All(&results)
        if limit < 0 {
            fn = c.Find(q).Skip(skip).All(&results)
        }
        return fn
    }

    search := func() error {
        return queryCollection(dbName, collection, dialURL, query)
    }

    err := search()
    if err != nil {
        errorCode = "error"
    }

    return
}

[]interface{}で受け取るもしくは、返り値として設定している部分は適宜使用する構造体のスライスに置き換えればカスタマイズできそうですね。
Searchはかなり厄介ですね。私もコード理解するのに苦労しました。queryはObjective-CのBlocksのような使い方ですね。queryをその場の引数で関数実装して、それをqueryCollection関数の引数で渡しています。
 次回はapp.goの中で具体的な処理を実装します。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6