|
@@ -9,6 +9,8 @@ import (
|
|
|
"net/http"
|
|
|
"runtime"
|
|
|
"strconv"
|
|
|
+ "html/template"
|
|
|
+ "sort"
|
|
|
)
|
|
|
|
|
|
type MessageStruct struct {
|
|
@@ -20,10 +22,16 @@ type World struct {
|
|
|
RandomNumber uint16 `json:"randomNumber"`
|
|
|
}
|
|
|
|
|
|
+type Fortune struct {
|
|
|
+ Id uint16 `json:"id"`
|
|
|
+ Message string `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(localhost: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 (
|
|
@@ -42,6 +50,7 @@ func main() {
|
|
|
}
|
|
|
http.HandleFunc("/json", jsonHandler)
|
|
|
http.HandleFunc("/db", dbHandler)
|
|
|
+ http.HandleFunc("/fortune", fortuneHandler)
|
|
|
http.ListenAndServe(":8080", nil)
|
|
|
}
|
|
|
|
|
@@ -66,3 +75,38 @@ 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) {
|
|
|
+ // the Fortune table contains 12 rows, and we'll add another Fortune ourselves
|
|
|
+ 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)
|
|
|
+ }
|
|
|
+
|
|
|
+ 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++
|
|
|
+ }
|
|
|
+ fortunes[i].Message = "Additional fortune added at request time."
|
|
|
+
|
|
|
+ sort.Sort(ByMessage{fortunes})
|
|
|
+ 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)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+type Fortunes []Fortune
|
|
|
+func (s Fortunes) Len() int { return len(s) }
|
|
|
+func (s Fortunes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
|
|
+type ByMessage struct{ Fortunes }
|
|
|
+func (s ByMessage) Less(i, j int) bool { return s.Fortunes[i].Message < s.Fortunes[j].Message }
|