Skip to content

Instantly share code, notes, and snippets.

@renatosuero
Created October 23, 2020 20:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatosuero/1cc0a031c485542d41276cd718382eaa to your computer and use it in GitHub Desktop.
Save renatosuero/1cc0a031c485542d41276cd718382eaa to your computer and use it in GitHub Desktop.
código criado para mostrar o recurso de lock no banco de dados postgres
/*
Disclaimer: tive 0 prioridade com o código, meu objetivo era mostrar o lock,
Usando apenas o bd acho que não seria tão "didático" e ai criei esse código.
Fiz ele porcamente pq não é objetivo escrever uma API, e tentei manter ele
compacto caso alguém queria ver fica mais fácil abrir só esse arquivo.
NÃO RECOMENDO SEGUIR NADA DESSE CÓDIGO!!!.
*/
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"time"
_ "github.com/lib/pq"
)
func main() {
http.HandleFunc("/booking", bookingHandler)
http.ListenAndServe(":80", nil)
}
func bookingHandler(w http.ResponseWriter, r *http.Request) {
db, err := sql.Open("postgres", "user=postgres password=123pass dbname=cinema sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close()
id, _ := r.URL.Query()["id"]
cliente, _ := r.URL.Query()["cliente"]
log.Printf("Checando assento %s para o cliente %s", id[0], cliente[0])
tx, _ := db.Begin()
var resultado int
err = tx.QueryRow("SELECT id FROM assentos WHERE id = $1 AND cliente = ''", id[0]).Scan(&resultado)
//err = tx.QueryRow("SELECT id FROM assentos WHERE id = $1 AND cliente = '' FOR UPDATE", id[0]).Scan(&resultado)
if err != nil && err != sql.ErrNoRows {
tx.Rollback()
log.Println("Erro executando a consulta", err)
http.Error(w, "OPS, um erro ", http.StatusInternalServerError)
return
}
if resultado == 0 {
tx.Rollback()
http.Error(w, "Sinto muito mas o assento não está disponível", http.StatusOK)
return
}
log.Printf("Processando assento %s para o cliente %s", id[0], cliente[0])
if cliente[0] == "Henrique" {
time.Sleep(2 * time.Second)
}
_, err = tx.Exec("UPDATE assentos SET cliente =$2 WHERE id=$1", id[0], cliente[0])
if err != nil {
tx.Rollback()
log.Printf("Unable to execute the query. %v", err)
http.Error(w, "OPS, um erro ", http.StatusInternalServerError)
return
}
tx.Commit()
w.WriteHeader(http.StatusOK)
log.Printf("%s reservou o assento %v ! \n", cliente[0], id[0])
fmt.Fprintf(w, fmt.Sprintf("%s reservou o assento %v ! \n", cliente[0], id[0]))
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment