猿问

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

我用一些CRUD方法编写了一个简单的MongoDB软件包:


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

}

我有一个server.go,在其中创建Http Server并具有用于不同URL的处理程序。我希望能够连接到MongoDB并在特定处理程序中调用AddToDo方法。我可以从服务器的主要方法连接到数据库:


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()

    }

但是我不确定如何从处理程序中调用mongoConn.AddToDo(title,description string)方法。我应该创建一个全局数据库连接变量吗?


梵蒂冈之花
浏览 206回答 2
2回答

倚天杖

两种简单的方法:1.全局数据库会话package mainimport (&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "log"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "./backend")var mongoConn * backend.MongoDBConnfunc AddHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; log.Printf("serving %v %v", r.Method, r.URL.Path[1:])&nbsp; &nbsp; if r.Method != "POST" {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintln(w, "Not POST Method ")&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; title := r.FormValue("title")&nbsp; &nbsp; description := r.FormValue("description")&nbsp; &nbsp; fmt.Fprintf(w, " title description %v %v", title, description)//I can't call mongoConn.AddToDo(title, description) from here&nbsp; &nbsp; mongoConn.AddToDo(title, description)}&nbsp; &nbsp;&nbsp;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) {&nbsp; &nbsp;fmt.Fprintln(w, AddForm)}func main() {&nbsp; &nbsp; &nbsp; &nbsp; //connect to mongoDB&nbsp; &nbsp; &nbsp; &nbsp;mongoConn = backend.NewMongoDBConn()&nbsp; &nbsp; &nbsp; &nbsp; _ = mongoConn.Connect("localhost")&nbsp; &nbsp; &nbsp; &nbsp; defer mongoConn.Stop()&nbsp; &nbsp; &nbsp; &nbsp; http.HandleFunc("/", Index)&nbsp; &nbsp; &nbsp; &nbsp; http.HandleFunc("/add", AddHandler)&nbsp; &nbsp; &nbsp; &nbsp; log.Println("Start Server:")&nbsp; &nbsp; &nbsp; &nbsp; err := http.ListenAndServe(":8080", nil)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("ListenAndServe:", err)&nbsp; &nbsp; &nbsp; &nbsp; }}2.每个请求都有一个新的数据库连接import (&nbsp; &nbsp; "./backend"&nbsp; &nbsp; &nbsp; &nbsp;//other boilerplate imports)func AddHandler(writer http.ResponseWriter, request *http.Request) {&nbsp; &nbsp; log.Printf("serving %v %v", request.Method, request.URL.Path[1:])&nbsp; &nbsp; if request.Method != "POST" {&nbsp; &nbsp; &nbsp; &nbsp; serve404(writer)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; title := request.FormValue("title")&nbsp; &nbsp; description := request.FormValue("description")&nbsp; &nbsp; fmt.Fprintf(writer, " title description %v %v", title, description)&nbsp; &nbsp; //................&nbsp; &nbsp; mongoConn := backend.NewMongoDBConn()&nbsp; &nbsp; _ = mongoConn.Connect("localhost")&nbsp; &nbsp; mongoConn.AddToDo(title, description)&nbsp; &nbsp; //....................&nbsp; &nbsp; mongoConn.Stop()}&nbsp;......更好的解决方案:您可以创建一个数据库会话池,然后在处理请求之前选择一个并放入该请求的上下文中。然后,在完成请求后,将连接推回池中。如果该池为空,则创建一个新的连接;如果该池已满,则关闭该连接

慕田峪4524236

是的,全球会议是处理此问题的简便方法。然后,在每个处理程序的顶部,您可以执行以下操作:func handler(...) {&nbsp; &nbsp; session := globalSession.Copy()&nbsp; &nbsp; defer session.Close()}这样每个处理程序都可以使用自己的会话。请注意,复制和关闭会话是廉价的操作,在内部将对连接池起作用,而不是为每个创建的会话建立新的连接。
随时随地看视频慕课网APP

相关分类

Go
我要回答