Browse Source

Begining of Go fortune test

Patrick Falls 12 years ago
parent
commit
8919128d7c
4 changed files with 63 additions and 3 deletions
  1. 1 0
      go/benchmark_config
  2. 39 3
      go/src/hello/hello.go
  3. 14 0
      go/templates/fortune.html
  4. 9 0
      go/templates/layout.html

+ 1 - 0
go/benchmark_config

@@ -6,6 +6,7 @@
       "json_url": "/json",
       "db_url": "/db",
       "query_url": "/db?queries=",
+      "fortune_url": "/fortune",
       "port": 8080,
       "sort": 27
     }

+ 39 - 3
go/src/hello/hello.go

@@ -20,10 +20,16 @@ type World struct {
 	RandomNumber uint16 `json:"randomNumber"`
 }
 
+type Fortune struct {
+	Id           uint16 `json:"id"`
+	Message      uint16 `json:"message"`
+}
+
 const (
-	DB_CONN_STR   = "benchmarkdbuser:benchmarkdbpass@tcp(172.16.98.98:3306)/hello_world?charset=utf8"
-	DB_SELECT_SQL = "SELECT id, randomNumber FROM World where id = ?;"
-	DB_ROWS       = 10000
+	DB_CONN_STR           = "benchmarkdbuser:benchmarkdbpass@tcp(172.16.98.98:3306)/hello_world?charset=utf8"
+	DB_SELECT_SQL         = "SELECT id, randomNumber FROM World where id = ?;"
+  DB_FORTUNE_SELECT_SQL = "SELECT id, message FROM Fortune;"
+	DB_ROWS               = 10000
 )
 
 var (
@@ -40,8 +46,12 @@ func main() {
 	if query, err = db.Prepare(DB_SELECT_SQL); err != nil {
 		log.Fatalf("Error preparing statement: %s", err)
 	}
+	if fortuneQuery, err = db.Query(DB_FORTUNE_SELECT_SQL); err != nil {
+		log.Fatalf("Error preparing statement: %s", err)
+	}
 	http.HandleFunc("/json", jsonHandler)
 	http.HandleFunc("/db", dbHandler)
+  http.HandleFunc("/fortune", fortuneHandler)
 	http.ListenAndServe(":8080", nil)
 }
 
@@ -66,3 +76,29 @@ func dbHandler(w http.ResponseWriter, r *http.Request) {
 	w.Header().Set("Content-Length", strconv.Itoa(len(j)))
 	w.Write(j)
 }
+
+func fortuneHandler(w http.ResponseWriter, r *http.Request) {
+  fortunes := make([]Fortune, 13)
+  
+  // Execute the query
+	rows, err := db.Query(DB_FORTUNE_SELECT_SQL)
+	if err != nil {
+		log.Fatalf("Error preparing statement: %s", err)
+	}
+  
+  var i := 0
+	// Fetch rows
+	for rows.Next() {
+		// get RawBytes from data
+		err = rows.Scan(&fortunes[i].id, &fortunes[i].message)
+		if err != nil {
+			panic(err.Error())
+		}
+		i++
+	}
+  
+  var tmpl = template.Must(template.ParseFiles("templates/layout.html", "templates/fortune.html"))
+  if err := tmpl.Execute(w, map[string]interface{} {"fortunes": fortunes}); err != nil {
+    http.Error(w, err.Error(), http.StatusInternalServerError)
+  }
+}

+ 14 - 0
go/templates/fortune.html

@@ -0,0 +1,14 @@
+{{define "content"}}
+<table>
+<tr>
+<th>id</th>
+<th>message</th>
+</tr>
+{{#fortunes}}
+<tr>
+<td>{{id}}</td>
+<td>{{message}}</td>
+</tr>
+{{/fortunes}}
+</table>
+{{end}}

+ 9 - 0
go/templates/layout.html

@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Fortunes</title>
+</head>
+<body>
+{{template "content" .}}
+</body>
+</html>