Explorar o código

Initial work on DB handler

Edward Bramanti %!s(int64=10) %!d(string=hai) anos
pai
achega
bcc8cd78d2
Modificáronse 1 ficheiros con 30 adicións e 2 borrados
  1. 30 2
      frameworks/Go/go-mongodb/src/hello/hello.go

+ 30 - 2
frameworks/Go/go-mongodb/src/hello/hello.go

@@ -12,6 +12,11 @@ import (
 const (
 	connectionString = "localhost"
 	helloWorldString = "Hello, world!"
+	worldRowCount    = 10000
+)
+
+var (
+	collection *mgo.Collection
 )
 
 type Message struct {
@@ -29,16 +34,19 @@ type Fortune struct {
 }
 
 func main() {
+	port := ":8228"
 	runtime.GOMAXPROCS(runtime.NumCPU())
 	session, err := mgo.Dial(connectionString)
 	if err != nil {
 		log.Fatalf("Error opening database: %v", err)
 	}
-	fmt.Println("Test")
 	defer session.Close()
 	session.SetPoolLimit(5)
+	collection = session.DB("hello_world").C("world")
+	http.HandleFunc("/db", dbHandler)
 	http.HandleFunc("/json", jsonHandler)
-	http.ListenAndServe(":8228", nil)
+	fmt.Println("Serving on http://localhost" + port)
+	http.ListenAndServe(port, nil)
 }
 
 // Test 1: JSON serialization
@@ -46,3 +54,23 @@ func jsonHandler(w http.ResponseWriter, r *http.Request) {
 	w.Header().Set("Content-Type", "application/javascript")
 	json.NewEncoder(w).Encode(&Message{helloWorldString})
 }
+
+func dbHandler(w http.ResponseWriter, r *http.Request) {
+	var world World
+	var randomNumber = rand.Intn(worldRowCount) + 1
+	query := bson.M{
+		"id": randomNumber,
+	}
+	if collection != nil {
+		if err := collection.Find(query).One(&World); err != nil {
+			log.Fatalf("Error finding world with id: %s", err.Error())
+			return
+		} else {
+			w.Header().Set("Content-Type", "application/json")
+			json.NewEncoder(w).Encode(&world)
+			return
+		}
+	} else {
+		log.Fatal("Collection not initialized properly")
+	}
+}