diff options
Diffstat (limited to 'backend/main.go')
| -rw-r--r-- | backend/main.go | 121 |
1 files changed, 82 insertions, 39 deletions
diff --git a/backend/main.go b/backend/main.go index ae39b46..66ab015 100644 --- a/backend/main.go +++ b/backend/main.go @@ -1,15 +1,18 @@ package main import ( + "context" + "encoding/json" "fmt" "log" "net/http" "os" "strconv" - "time" + "strings" - "github.com/jmoiron/sqlx" - _ "github.com/lib/pq" + "github.com/jackc/pgx/v5" + + "iosdc-code-battle-poc/db" ) type Config struct { @@ -22,8 +25,6 @@ type Config struct { var config *Config -var db *sqlx.DB - func loadEnv() (*Config, error) { dbHost, exists := os.LookupEnv("ALBATROSS_DB_HOST") if !exists { @@ -84,37 +85,81 @@ func startGame(game *Game) { } func handleGolfPost(w http.ResponseWriter, r *http.Request) { - var yourTeam string - waitingGolfGames := []Game{} - err := db.Select(&waitingGolfGames, "SELECT * FROM games WHERE type = $1 AND state = $2 ORDER BY created_at", gameTypeGolf, gameStateWaiting) - if err != nil { - http.Error(w, "Error getting games", http.StatusInternalServerError) - return - } - if len(waitingGolfGames) == 0 { - _, err = db.Exec("INSERT INTO games (type, state) VALUES ($1, $2)", gameTypeGolf, gameStateWaiting) - if err != nil { - http.Error(w, "Error creating game", http.StatusInternalServerError) - return - } - waitingGolfGames = []Game{} - err = db.Select(&waitingGolfGames, "SELECT * FROM games WHERE type = $1 AND state = $2 ORDER BY created_at", gameTypeGolf, gameStateWaiting) + /* + var yourTeam string + waitingGolfGames := []Game{} + err := db.Select(&waitingGolfGames, "SELECT * FROM games WHERE type = $1 AND state = $2 ORDER BY created_at", gameTypeGolf, gameStateWaiting) if err != nil { http.Error(w, "Error getting games", http.StatusInternalServerError) return } - yourTeam = "a" - startGame(&waitingGolfGames[0]) - } else { - yourTeam = "b" - db.Exec("UPDATE games SET state = $1 WHERE game_id = $2", gameStateReady, waitingGolfGames[0].GameID) - } - waitingGame := waitingGolfGames[0] + if len(waitingGolfGames) == 0 { + _, err = db.Exec("INSERT INTO games (type, state) VALUES ($1, $2)", gameTypeGolf, gameStateWaiting) + if err != nil { + http.Error(w, "Error creating game", http.StatusInternalServerError) + return + } + waitingGolfGames = []Game{} + err = db.Select(&waitingGolfGames, "SELECT * FROM games WHERE type = $1 AND state = $2 ORDER BY created_at", gameTypeGolf, gameStateWaiting) + if err != nil { + http.Error(w, "Error getting games", http.StatusInternalServerError) + return + } + yourTeam = "a" + startGame(&waitingGolfGames[0]) + } else { + yourTeam = "b" + db.Exec("UPDATE games SET state = $1 WHERE game_id = $2", gameStateReady, waitingGolfGames[0].GameID) + } + waitingGame := waitingGolfGames[0] - http.Redirect(w, r, fmt.Sprintf("/golf/%d/%s/", waitingGame.GameID, yourTeam), http.StatusSeeOther) + http.Redirect(w, r, fmt.Sprintf("/golf/%d/%s/", waitingGame.GameID, yourTeam), http.StatusSeeOther) + */ } -func handleApiLogin(w http.ResponseWriter, r *http.Request) { +func handleApiLogin(w http.ResponseWriter, r *http.Request, queries *db.Queries) { + type LoginRequestData struct { + Username string `json:"username"` + Password string `json:"password"` + } + + type LoginResponseData struct { + UserId int `json:"userId"` + } + + ctx := r.Context() + + contentType := r.Header.Get("Content-Type") + if !strings.HasPrefix(contentType, "application/json") { + http.Error(w, "Content-Type is not application/json", http.StatusBadRequest) + return + } + + var requestData LoginRequestData + decoder := json.NewDecoder(r.Body) + err := decoder.Decode(&requestData) + if err != nil { + http.Error(w, "Failed to decode JSON", http.StatusBadRequest) + return + } + + userId, err := authLogin(ctx, queries, requestData.Username, requestData.Password) + if err != nil { + http.Error(w, "Login failed", http.StatusUnauthorized) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + responseData := LoginResponseData{ + UserId: userId, + } + encoder := json.NewEncoder(w) + err = encoder.Encode(responseData) + if err != nil { + http.Error(w, "Failed to encode JSON", http.StatusInternalServerError) + return + } } func main() { @@ -125,17 +170,15 @@ func main() { return } - for i := 0; i < 5; i++ { - db, err = sqlx.Connect("postgres", fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", config.dbHost, config.dbPort, config.dbUser, config.dbPassword, config.dbName)) - if err == nil { - break - } - time.Sleep(5 * time.Second) - } + ctx := context.Background() + + conn, err := pgx.Connect(ctx, fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", config.dbHost, config.dbPort, config.dbUser, config.dbPassword, config.dbName)) if err != nil { log.Fatalf("Error connecting to db %v", err) } - defer db.Close() + defer conn.Close(ctx) + + queries := db.New(conn) server := http.NewServeMux() @@ -194,8 +237,8 @@ func main() { serveWs(hub, w, r, team) }) - server.HandleFunc("POST /api/login/{$}", func(w http.ResponseWriter, r *http.Request) { - handleApiLogin(w, r) + server.HandleFunc("POST /api/login", func(w http.ResponseWriter, r *http.Request) { + handleApiLogin(w, r, queries) }) defer func() { |
