Last active
August 29, 2015 14:23
-
-
Save jwo/26a542f04bcf303328fd to your computer and use it in GitHub Desktop.
Sample Go that will serve some data, in a postgres table, as JSON the way Ember Data wants.
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 ( | |
"database/sql" | |
"github.com/ant0ine/go-json-rest/rest" | |
_ "github.com/lib/pq" | |
"log" | |
"net/http" | |
) | |
func main() { | |
api := rest.NewApi() | |
api.Use(rest.DefaultDevStack...) | |
router, err := rest.MakeRouter( | |
rest.Get("/contacts", GetAllContacts), | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
api.SetApp(router) | |
log.Fatal(http.ListenAndServe(":3000", api.MakeHandler())) | |
} | |
type Contact struct { | |
Id string `json:"id"` | |
FirstName string `json:"first_name"` | |
LastName string `json:"last_name"` | |
CompanyName string `json:"company_name"` | |
Email string `json:"email"` | |
} | |
type Contacts struct { | |
Contacts []Contact `json:"contacts"` | |
} | |
func GetAllContacts(w rest.ResponseWriter, r *rest.Request) { | |
db, err := sql.Open("postgres", "user=jwo dbname=contacts_development sslmode=disable") | |
if err != nil { | |
log.Fatal(err) | |
} | |
rows, err := db.Query("SELECT id, first_name, last_name, email, company_name FROM contacts") | |
if err != nil { | |
log.Fatal(err) | |
} | |
contacts := []Contact{} | |
for rows.Next() { | |
contact := Contact{} | |
rows.Scan(&contact.Id, &contact.FirstName, &contact.LastName, &contact.Email, &contact.CompanyName) | |
contacts = append(contacts, contact) | |
} | |
contactRoot := Contacts{} | |
contactRoot.Contacts = contacts | |
w.WriteJson(&contactRoot) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment