-
-
Save IgorMing/27044a231f037d9bf3c2fb2a20496f80 to your computer and use it in GitHub Desktop.
Código para o Igão.
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 ( | |
"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