How to do it…

  1. Install the gopkg.in/mgo.v2, gopkg.in/mgo.v2/bson, and github.com/gorilla/mux packages, using the go get command, as follows:
$ go get gopkg.in/mgo.v2
$ go get gopkg.in/mgo.v2/bson
$ go get github.com/gorilla/mux
  1. Create read-record-mongodb.go. Then we connect to the MongoDB database, read all the documents from an employee collection, marshal the list to JSON, and write it to an HTTP response stream, as follows:
package main
import
(
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
MONGO_DB_URL = "127.0.0.1"
)
var session *mgo.Session
var connectionError error
func init()
{
session, connectionError = mgo.Dial(MONGO_DB_URL)
if connectionError != nil
{
log.Fatal("error connecting to database :: ", connectionError)
}
session.SetMode(mgo.Monotonic, true)
}
type Employee struct
{
Id int `json:"uid"`
Name string `json:"name"`
}
func readDocuments(w http.ResponseWriter, r *http.Request)
{
log.Print("reading documents from database")
var employees []Employee
collection := session.DB("mydb").C("employee")
err := collection.Find(bson.M{}).All(&employees)
if err != nil
{
log.Print("error occurred while reading documents from
database :: ", err)
return
}
json.NewEncoder(w).Encode(employees)
}
func main()
{
router := mux.NewRouter()
router.HandleFunc("/employees", readDocuments).Methods("GET")
defer session.Close()
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, router)
if err != nil
{
log.Fatal("error starting http server :: ", err)
return
}
}
  1. Run the program with the following command: 
$ go run read-record-mongodb.go
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.189.23