Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I call mongoDB CRUD method from handler?
    primarykey
    data
    text
    <p>I've written a simple MongoDB package with some CRUD methods:</p> <pre><code>package backend import "labix.org/v2/mgo" type MongoDBConn struct { session *mgo.Session } type ToDo struct { Title string Description string } func NewMongoDBConn() *MongoDBConn { return &amp;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(&amp;ToDo{title, description}) if err != nil { panic(err) } return nil } </code></pre> <p>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:</p> <pre><code>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() } </code></pre> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload