From 325291d092cc55580a03032d8e3c8af362d3f143 Mon Sep 17 00:00:00 2001 From: Philip O'Toole Date: Sat, 23 Aug 2014 15:27:15 -0700 Subject: [PATCH] All queries successfully returned as JSON --- src/github.com/otoolep/rqlite/db/db.go | 20 +++++++++++-------- .../otoolep/rqlite/server/server.go | 8 ++++++-- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/github.com/otoolep/rqlite/db/db.go b/src/github.com/otoolep/rqlite/db/db.go index 3b991140..8088083c 100644 --- a/src/github.com/otoolep/rqlite/db/db.go +++ b/src/github.com/otoolep/rqlite/db/db.go @@ -19,6 +19,9 @@ type DB struct { dbConn *sql.DB } +type RowResult map[string]string +type RowResults []map[string]string + // Creates a new database. func New(dir string) *DB { path := path.Join(dir, dbName) @@ -35,16 +38,17 @@ func New(dir string) *DB { } // Executes the query. -func (db *DB) Query(query string) string { +func (db *DB) Query(query string) RowResults { rows, err := db.dbConn.Query(query) if err != nil { fmt.Println(err.Error()) } defer rows.Close() + results := make(RowResults, 0) + columns, _ := rows.Columns() rawResult := make([][]byte, len(columns)) - result := make([]string, len(columns)) dest := make([]interface{}, len(columns)) // A temporary interface{} slice for i, _ := range rawResult { dest[i] = &rawResult[i] // Put pointers to each string in the interface slice @@ -53,20 +57,20 @@ func (db *DB) Query(query string) string { for rows.Next() { err = rows.Scan(dest...) if err != nil { - fmt.Println("Failed to scan row", err) + log.Fatal("Failed to scan row", err) } + r := make(RowResult) for i, raw := range rawResult { if raw == nil { - result[i] = "null" + r[columns[i]] = "null" } else { - result[i] = string(raw) + r[columns[i]] = string(raw) } } - - fmt.Printf("%#v\n", result) + results = append(results, r) } - return "query complete response" // Inefficient? + return results } // Sets the value for a given key. diff --git a/src/github.com/otoolep/rqlite/server/server.go b/src/github.com/otoolep/rqlite/server/server.go index 58e14a2a..712966c9 100644 --- a/src/github.com/otoolep/rqlite/server/server.go +++ b/src/github.com/otoolep/rqlite/server/server.go @@ -164,8 +164,12 @@ func (s *Server) readHandler(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusBadRequest) return } - value := s.db.Query(string(b)) - w.Write([]byte(value)) + b, err = json.Marshal(s.db.Query(string(b))) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Write([]byte(b)) } func (s *Server) writeHandler(w http.ResponseWriter, req *http.Request) {