Skip to content

Instantly share code, notes, and snippets.

@cutalion
Created July 25, 2017 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cutalion/d18952657791ccf1fd5a563594ea0c06 to your computer and use it in GitHub Desktop.
Save cutalion/d18952657791ccf1fd5a563594ea0c06 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"log"
"database/sql"
_ "github.com/lib/pq"
"encoding/json"
)
var db, _ = sql.Open("postgres", "user=cutalion dbname=ten_thousand_users_ruby")
func typeof(v interface{}) string {
return fmt.Sprintf("%T", v)
}
type User struct {
ID int `json:"id,omitempty"`
Username string `json:"firstname,omitempty"`
Email string `json:"lastname,omitempty"`
}
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var (
id int
username string
email string
people []User
)
rows, _ := db.Query("select * from users")
defer rows.Close()
for rows.Next() {
rows.Scan(&id, &username, &email)
people = append(people, User{ID: id, Username: username, Email: email})
}
w.Header().Set("Content-Type", "application/json")
response, _ := json.Marshal(people)
fmt.Fprint(w, string(response))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
log.Fatal(http.ListenAndServe(":8080", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment