Created
July 25, 2017 17:05
-
-
Save cutalion/d18952657791ccf1fd5a563594ea0c06 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"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