douzong2206 2012-12-24 08:16
浏览 71
已采纳

如何从处理程序调用mongoDB CRUD方法?

I've written a simple MongoDB package with some CRUD methods:

package backend

import "labix.org/v2/mgo"

type MongoDBConn struct {
    session *mgo.Session
}

type ToDo struct {
    Title       string
    Description string
}

func NewMongoDBConn() *MongoDBConn {
    return &MongoDBConn{}
}

func (m *MongoDBConn) Connect(url string) *mgo.Session {
    session, err := mgo.Dial(url)
    if err != nil {
        panic(err)
    }
    m.session = session
    return m.session
}

func (m *MongoDBConn) Stop() {
    m.session.Close()
}

func (m *MongoDBConn) AddToDo(title, description string) (err error) {
    c := m.session.DB("test").C("people")
    err = c.Insert(&ToDo{title, description})
    if err != nil {
        panic(err)
    }
    return nil
}

I have a server.go where I create a Http Server and have handlers for the different URLs. I'd like to be able to connect to MongoDB and call the AddToDo method within a specific handler. I can connect to the DB from the main method of my server:

import (
    "./backend"
       //other boilerplate imports
)

func AddHandler(writer http.ResponseWriter, request *http.Request) {
    log.Printf("serving %v %v", request.Method, request.URL.Path[1:])
    if request.Method != "POST" {
        serve404(writer)
        return
    }
    title := request.FormValue("title")
    description := request.FormValue("description")
    fmt.Fprintf(writer, " title description %v %v", title, description)
//I can't call mongoConn.AddToDo(title, description) from here

}    
func main() {
        //connect to mongoDB
        mongoConn := backend.NewMongoDBConn()
        _ = mongoConn.Connect("localhost")
        defer mongoConn.Stop()
    }

But I'm not sure how to call mongoConn.AddToDo(title, description string) method from the handler. Should I create a global db connection variable?

  • 写回答

2条回答 默认 最新

  • douzhendi4559 2012-12-24 11:42
    关注

    Two simple method:

    1.global database session

    package main
    
    
    import (
        "net/http"
        "log"
        "fmt"
        "./backend"
    )
    
    
    var mongoConn * backend.MongoDBConn
    
    func AddHandler(w http.ResponseWriter, r *http.Request) {
        log.Printf("serving %v %v", r.Method, r.URL.Path[1:])
        if r.Method != "POST" {
            fmt.Fprintln(w, "Not POST Method ")
            return
        }
        title := r.FormValue("title")
        description := r.FormValue("description")
    
    
    
        fmt.Fprintf(w, " title description %v %v", title, description)
    //I can't call mongoConn.AddToDo(title, description) from here
        mongoConn.AddToDo(title, description)
    }    
    
    const AddForm = `
    <html><body>
    <form method="POST" action="/add">
    Name: <input type="text" name="title">
    Age: <input type="text" name="description">
    <input type="submit" value="Add">
    </form>
    </body></html>
    `
    func Index(w http.ResponseWriter, r *http.Request) {
       fmt.Fprintln(w, AddForm)
    }
    
    func main() {
            //connect to mongoDB
    
    
           mongoConn = backend.NewMongoDBConn()
            _ = mongoConn.Connect("localhost")
            defer mongoConn.Stop()
    
            http.HandleFunc("/", Index)
            http.HandleFunc("/add", AddHandler)
    
            log.Println("Start Server:")
            err := http.ListenAndServe(":8080", nil)
    
            if err != nil {
                log.Fatal("ListenAndServe:", err)
            }
    }
    

    2.a new db connection on every request

    import (
        "./backend"
           //other boilerplate imports
    )
    
    func AddHandler(writer http.ResponseWriter, request *http.Request) {
        log.Printf("serving %v %v", request.Method, request.URL.Path[1:])
        if request.Method != "POST" {
            serve404(writer)
            return
        }
        title := request.FormValue("title")
        description := request.FormValue("description")
        fmt.Fprintf(writer, " title description %v %v", title, description)
        //................
        mongoConn := backend.NewMongoDBConn()
        _ = mongoConn.Connect("localhost")
        mongoConn.AddToDo(title, description)
        //....................
        mongoConn.Stop()
    
    } 
    
    ......
    

    a better solution:

    You could create a pool of db sessions, then before processing the request you pick one and put in the context of that request. Then after the request is done you push the connection back to the pool.

    If the pool is empty you create a new connection If the pool is full you close the connection

    For more information, click here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘