|
@@ -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")
|
|
|
+ }
|
|
|
+}
|