-
-
Save aeroproof/53f4447f876d6dc28d1b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"code.google.com/p/gorilla/mux" | |
"database/sql" | |
"encoding/json" | |
"github.com/injekt/sqlmap" | |
_ "github.com/lib/pq" | |
"net/http" | |
) | |
var DB *sql.DB | |
var router *mux.Router | |
func QueryToJson(query string) []byte { | |
results, err := sqlmap.Query(DB, query) | |
if err != nil { | |
return []byte{} // FIXME | |
} | |
jsonStr, err := json.Marshal(results) | |
if err != nil { | |
return []byte{} // FIXME | |
} | |
return jsonStr | |
} | |
func mapQuery(path, query string) { | |
router.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { | |
w.Write(QueryToJson(query)) | |
}) | |
} | |
func main() { | |
var err error | |
DB, err = sql.Open("postgres", "user=lee dbname=xxx sslmode=disable") | |
if err != nil { | |
panic(err) | |
} | |
router = mux.NewRouter() | |
router.Headers("Content-Type", "application/json") | |
// collections | |
mapQuery("/users", "SELECT id, email FROM users ORDER BY id") | |
// *snip* | |
http.ListenAndServe(":3000", router) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment