Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# LetsGo: A Real-time Full-Stack Web Application

[![GitHub Actions CI Status](https://github.com/dann-huang/letsGo/actions/workflows/pr-checks.yml/badge.svg)](https://github.com/dann-huang/letsGo/actions/workflows/pr-checks.yml)
[![GitHub Actions Deployment Status](https://github.com/dann-huang/letsGo/actions/workflows/build-deploy.yml/badge.svg)](https://github.com/dann-huang/letsGo/actions/workflows/build-deploy.yml)
[![GitHub Actions Deployment Status](https://github.com/dann-huang/letsGo/actions/workflows/build-n-deploy.yml/badge.svg)](https://github.com/dann-huang/letsGo/actions/workflows/build-n-deploy.yml)

LetsGo is a personal project and portfolio piece showcasing a full-stack web application designed for interactive, real-time experiences. It highlights expertise in modern backend (Go), frontend (Next.js), and robust containerized deployment with Docker, Nginx, PostgreSQL, and Redis.

Expand Down Expand Up @@ -114,5 +114,5 @@ This will build the Docker images and start all services. The frontend will be a
This project uses GitHub Actions for continuous integration and deployment. The workflow is defined in `.github/workflows/`:

- `pr-checks.yml`: Runs on every pull request to ensure that the frontend and backend Docker images can be built successfully.
- `build-deploy.yml`: Deploys the application to the production server upon a push to the `main` branch.
- `build-n-deploy.yml`: Deploys the application to the production server upon a push to the `main` branch.

1 change: 1 addition & 0 deletions backend/cmd/migrate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func RunInitialSchema(db *sql.DB) error {
return nil
}

//nolint:unused
func main() {
appConfig, err := config.Load()
if err != nil {
Expand Down
15 changes: 9 additions & 6 deletions backend/cmd/web/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,20 @@ func main() {
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)

games := game.NewRegistry()
games.Register("connect4", game.NewConnect4())
games.Register("tictactoe", game.NewTicTacToe())
gameReg := game.NewRegistry()
gameReg.RegisterAll()

r.Route("/api", func(api chi.Router) {
api.Get("/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok"}`))
if _, err := w.Write([]byte(`{"status":"ok"}`)); err != nil {
slog.Error("failed to write health response", "error", err)
}
})

api.Mount("/auth", authModule.Router())
api.Mount("/live", live.Router(userAccMdw, userCtxKey, games, appCfg.WS))
api.Mount("/live", live.Router(userAccMdw, userCtxKey, gameReg, appCfg.WS))
})

// static pages
Expand All @@ -74,5 +75,7 @@ func main() {
// r.Mount("/", external.FrontendRevProxy(cfg.FrontendUrl))

println("---Server start---")
http.ListenAndServe(":3333", r)
if err := http.ListenAndServe(":3333", r); err != nil {
slog.Error("server error", "error", err)
}
}
3 changes: 3 additions & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ require (
golang.org/x/crypto v0.38.0
)

require golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c // indirect

require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/corentings/chess/v2 v2.0.9
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/go-playground/locales v0.14.1 // indirect
Expand Down
4 changes: 4 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/corentings/chess/v2 v2.0.9 h1:DRRxTFm1iLpax1hAfor2Q96WPN7OI8XjxoNiwQDO2Lk=
github.com/corentings/chess/v2 v2.0.9/go.mod h1:JhWYDbjY81/7NECXrLzz4g2r9taaMEXvyqS4gYZciVE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
Expand Down Expand Up @@ -38,6 +40,8 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc=
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU=
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0=
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
Expand Down
34 changes: 22 additions & 12 deletions backend/internal/auth/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ type handlerImpl struct {

func (h *handlerImpl) indexHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"message": "Auth is running"}`))
if err := util.RespondJSON(w, http.StatusOK, map[string]string{"message": "Auth is running"}); err != nil {
slog.Error("failed to write health response", "error", err)
}
}
}

Expand All @@ -46,7 +47,7 @@ func (h *handlerImpl) setAuthCookie(w http.ResponseWriter, name, value, path str
Name: name,
Value: value,
// Quoted,
Path: path,
Path: path,
// Domain: h.config.Domain, // not needed when share domains apparently
Expires: expires,
// RawExpires,
Expand Down Expand Up @@ -80,11 +81,13 @@ func (h *handlerImpl) registerHandler() http.HandlerFunc {
}
return
}
util.RespondJSON(w, http.StatusOK, map[string]string{
if err := util.RespondJSON(w, http.StatusOK, map[string]string{
"message": "Success",
"username": usr.Username,
"displayname": usr.DisplayName,
})
}); err != nil {
slog.Error("failed to write register response", "error", err)
}
}
}

Expand All @@ -110,28 +113,33 @@ func (h *handlerImpl) loginHandler() http.HandlerFunc {
h.setAuthCookie(w, h.config.AccCookieName, access, "/", accExpire)
h.setAuthCookie(w, h.config.RefCookieName, refresh, "/api/auth", refExpire)

util.RespondJSON(w, http.StatusOK, map[string]any{
if err := util.RespondJSON(w, http.StatusOK, map[string]any{
"message": "login success",
"username": usr.Username,
"displayname": usr.DisplayName,
"accessExpires": accExpire.UnixMilli(),
"refreshExpires": refExpire.UnixMilli(),
})
}); err != nil {
slog.Error("failed to write login response", "error", err)
}
}
}

func (h *handlerImpl) logoutHandler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
refreshCookie, err := r.Cookie(h.config.RefCookieName)
if err == nil {
h.service.logoutUser(r.Context(), refreshCookie.Value)

if err := h.service.logoutUser(r.Context(), refreshCookie.Value); err != nil {
slog.Error("failed to logout user", "error", err)
}
h.setAuthCookie(w, h.config.AccCookieName, "", "/", time.Unix(0, 0))
h.setAuthCookie(w, h.config.RefCookieName, "", "/api/auth", time.Unix(0, 0))
} else {
slog.Error(err.Error())
}
util.RespondJSON(w, http.StatusOK, map[string]string{"message": "logout success"})
if err := util.RespondJSON(w, http.StatusOK, map[string]string{"message": "logout success"}); err != nil {
slog.Error("failed to write logout response", "error", err)
}
}
}

Expand All @@ -156,10 +164,12 @@ func (h *handlerImpl) refreshHandler() http.HandlerFunc {
h.setAuthCookie(w, h.config.AccCookieName, access, "/", accExpire)
h.setAuthCookie(w, h.config.RefCookieName, refresh, "/api/auth", refExpire)

util.RespondJSON(w, http.StatusOK, map[string]any{
if err := util.RespondJSON(w, http.StatusOK, map[string]any{
"message": "refresh success",
"accessExpires": accExpire.UnixMilli(),
"refreshExpires": refExpire.UnixMilli(),
})
}); err != nil {
slog.Error("failed to write refresh response", "error", err)
}
}
}
5 changes: 2 additions & 3 deletions backend/internal/auth/module.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package auth

import (
"github.com/go-chi/chi/v5"

"letsgo/internal/config"
"letsgo/internal/repo"
"letsgo/internal/token"

"github.com/go-chi/chi/v5"
)

type AuthModule interface {
Expand All @@ -17,7 +17,6 @@ type authImpl struct {
}

func NewModule(userRepo repo.UserRepo, kvStore repo.KVStore, accMngr token.UserManager, config *config.Auth) AuthModule {

service := newService(accMngr, userRepo, kvStore, config)
handler := newHandler(service, config)
router := newRouter(handler)
Expand Down
119 changes: 119 additions & 0 deletions backend/internal/game/chess.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package game

import (
"encoding/json"
"fmt"
"time"

"github.com/corentings/chess/v2"
)

type chessGame struct {
baseGame
game *chess.Game
}

func newChess() Factory {
return func(creator string, payload json.RawMessage) (Game, error) {
game := &chessGame{
baseGame: newBase(2, "chess"),
game: chess.NewGame(),
}
game.Players = []string{creator}
game.Turn = 0
return game, nil
}
}

func rowCol2Move(x, y int) string {
return fmt.Sprintf("%c%d", 'a'+x, 8-y)
}

func (g *chessGame) Move(sender string, payload json.RawMessage) (*GameState, error) {
mv, _, err := g.validateMove(sender, payload)
if err != nil {
return nil, err
}

moveStr := rowCol2Move(mv.From.Row, mv.From.Col) + rowCol2Move(mv.To.Row, mv.To.Col)
if mv.Change != "" {
moveStr += mv.Change
}
notation := chess.UCINotation{}
move, err := notation.Decode(g.game.Position(), moveStr)
if err != nil {
return nil, fmt.Errorf("invalid move format %q: %w", moveStr, err)
}

if err := g.game.Move(move, nil); err != nil {
return nil, fmt.Errorf("illegal move %q: %w", moveStr, err)
}

if g.game.Outcome() != chess.NoOutcome {
g.Status = StatusFin
g.EndedAt = time.Now()
switch g.game.Outcome() {
case chess.WhiteWon:
g.Winner = g.Players[0]
case chess.BlackWon:
g.Winner = g.Players[1]
}
}

g.Turn = 1 - g.Turn

return g.State(), nil
}

func pieceToCode(piece chess.Piece) int {
var code int
switch piece.Type() {
case chess.King:
code += 1
case chess.Queen:
code += 2
case chess.Rook:
code += 3
case chess.Bishop:
code += 4
case chess.Knight:
code += 5
case chess.Pawn:
code += 6
}
if piece.Color() == chess.White {
code += 10
}
return code
}

func (g *chessGame) State() *GameState {
board := make([][]int, 8)
for i := 0; i < 8; i++ {
board[i] = make([]int, 8)
for j := 0; j < 8; j++ {
sq := chess.Square((7-i)*8 + j)
piece := g.game.Position().Board().Piece(sq)
if piece != chess.NoPiece {
board[i][j] = pieceToCode(piece)
} else {
board[i][j] = 0
}
}
}

state := g.state(board)
return state
}

func (g *chessGame) Tick() (*GameState, string) {
if g.handleTimeout() {
return g.State(), TickBroadcast
}

if g.Status == StatusFin && time.Since(g.EndedAt) > CleanupDelay {
return nil, TickFinished
}

return nil, TickNoChange
}
Loading