Skip to content

Instantly share code, notes, and snippets.

@nubunto
Last active July 7, 2016 02:15
Show Gist options
  • Save nubunto/7ed219bdff68bfceb6c79fc151e9b235 to your computer and use it in GitHub Desktop.
Save nubunto/7ed219bdff68bfceb6c79fc151e9b235 to your computer and use it in GitHub Desktop.
Código para o Igão.
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
"net/http"
_ "github.com/lib/pq"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
type JSONBody struct {
User `json:"user"`
}
type JSONResponse struct {
Ok bool `json:"ok"`
Message string `json:"message"`
}
func main() {
db, err := sql.Open("postgres", "user=postgres password=postgres dbname=postgres")
if err != nil {
log.Fatal(err)
}
if err := db.Ping(); err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello world")
})
mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
var js JSONBody
dec := json.NewDecoder(r.Body)
enc := json.NewEncoder(w)
if err := dec.Decode(&js); err != nil {
jsResp := JSONResponse{
Ok: false,
Message: err.Error(),
}
if err = enc.Encode(&jsResp); err != nil {
http.Error(w, "que porra é essa", http.StatusBadRequest)
return
}
}
var id int
db.QueryRow("INSERT INTO USUARIO (name, age) VALUES ($1, $2) RETURNING ID", js.Name, js.Age).Scan(&id)
jsResp := JSONResponse{
Ok: true,
Message: "ok",
}
if err := enc.Encode(&jsResp); err != nil {
http.Error(w, "que porra é essa", http.StatusBadRequest)
return
}
}
})
http.ListenAndServe(":8080", mux)
}
/*
var id int
db.QueryRow("INSERT INTO USUARIO (name, age) VALUES ($1, $2) RETURNING ID", "bruno", 21).Scan(&id)
rows, err := db.Query("SELECT name, age FROM Usuario WHERE id = $1", id)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
users := make([]User, 0)
for rows.Next() {
var user User
err = rows.Scan(&user.name, &user.age)
if err != nil {
log.Fatal(err)
}
users = append(users, user)
}
fmt.Println(users)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment