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: 4 additions & 0 deletions cmd/feelbeatserver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import (
"net/http"
"os"

"github.com/feelbeatapp/feelbeatserver/internal/infra/auth"
"github.com/feelbeatapp/feelbeatserver/internal/infra/fblog"
"github.com/feelbeatapp/feelbeatserver/internal/infra/ws"
"github.com/feelbeatapp/feelbeatserver/internal/lib/component"
"github.com/feelbeatapp/feelbeatserver/internal/lib/roomrepository"
"github.com/knadh/koanf/v2"
)

Expand Down Expand Up @@ -39,6 +41,8 @@ func main() {
ws.ServeWebsockets(hub, w, r)
})

setupAPI(auth.AuthorizeThroughSpotify, roomrepository.NewInMemoryRoomRepository())

fblog.Info(component.FeelBeatServer, "Server started", "port", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", port), nil))
}
25 changes: 25 additions & 0 deletions cmd/feelbeatserver/setupapi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

import (
"github.com/feelbeatapp/feelbeatserver/internal/infra/api/roomapi"
"github.com/feelbeatapp/feelbeatserver/internal/infra/auth"
"github.com/feelbeatapp/feelbeatserver/internal/infra/fblog"
"github.com/feelbeatapp/feelbeatserver/internal/lib/component"
"github.com/feelbeatapp/feelbeatserver/internal/lib/roomrepository"
)

const baseUrl = "/api/v1"

// TODO: Add contexts to api handler for graceful shutdown

func setupAPI(authWrapper auth.AuthWrapper, roomRepo roomrepository.RoomRepository) {
roomApi := roomapi.NewRoomApi(roomRepo)

handlers := []func(string, auth.AuthWrapper){roomApi.ServeCreateGame}

fblog.Info(component.Api, "Setting up REST API", "handlers count", len(handlers))

for _, f := range handlers {
f(baseUrl, authWrapper)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require github.com/gorilla/websocket v1.5.3

require (
github.com/buger/jsonparser v1.1.1
github.com/google/uuid v1.6.0
github.com/knadh/koanf/parsers/toml v0.1.0
github.com/knadh/koanf/providers/env v1.0.0
github.com/knadh/koanf/providers/file v1.1.2
Expand All @@ -26,7 +27,6 @@ require (
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.5.2 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/sys v0.28.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NIs=
Expand Down Expand Up @@ -40,8 +42,6 @@ github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3v
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
Expand Down
16 changes: 16 additions & 0 deletions internal/infra/api/logapicall.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package api

import (
"net/http"

"github.com/feelbeatapp/feelbeatserver/internal/infra/fblog"
"github.com/feelbeatapp/feelbeatserver/internal/lib/component"
)

func LogApiCall(userId string, req *http.Request) {
fblog.Info(component.Api, req.Method+" "+req.URL.String(), "user", userId, "ip", req.RemoteAddr)
}

func LogApiError(message string, err error, userId string, req *http.Request) {
fblog.Error(component.Api, req.Method+" "+req.URL.String()+": "+message, "err", err, "user", userId, "ip", req.RemoteAddr)
}
15 changes: 15 additions & 0 deletions internal/infra/api/parsebody.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package api

import (
"encoding/json"
"io"
)

func ParseBody(body io.ReadCloser, out any) error {
bytes, err := ReadBody(body)
if err != nil {
return err
}

return json.Unmarshal(bytes, out)
}
16 changes: 16 additions & 0 deletions internal/infra/api/readbody.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package api

import (
"io"
)

func ReadBody(body io.ReadCloser) ([]byte, error) {
defer body.Close()

bytes, err := io.ReadAll(body)
if err != nil {
return []byte{}, err
}

return bytes, nil
}
63 changes: 63 additions & 0 deletions internal/infra/api/roomapi/creategame.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package roomapi

import (
"encoding/json"
"errors"
"fmt"
"net/http"

"github.com/feelbeatapp/feelbeatserver/internal/infra/api"
"github.com/feelbeatapp/feelbeatserver/internal/infra/auth"
"github.com/feelbeatapp/feelbeatserver/internal/infra/fblog"
"github.com/feelbeatapp/feelbeatserver/internal/lib/component"
"github.com/feelbeatapp/feelbeatserver/internal/lib/feelbeaterror"
"github.com/feelbeatapp/feelbeatserver/internal/lib/room"
)

type createGameResponse struct {
RoomId string `json:"roomId"`
}

func (r RoomApi) createGameHandler(userId string, res http.ResponseWriter, req *http.Request) {
var payload room.RoomSettings
err := api.ParseBody(req.Body, &payload)
if err != nil {
http.Error(res, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
fblog.Error(component.Api, "Error: ", "err", err)
return
}

roomId, err := r.roomRepo.CreateRoom(userId, payload)
if err != nil {
var fbError *feelbeaterror.FeelBeatError
if errors.As(err, &fbError) {
http.Error(res, string(fbError.UserMessage), feelbeaterror.StatusCode(fbError.UserMessage))
} else {
http.Error(res, feelbeaterror.Default, feelbeaterror.StatusCode(feelbeaterror.Default))
}

api.LogApiError("Create room failed", err, userId, req)
return
}

resJson, err := json.Marshal(createGameResponse{
RoomId: roomId,
})
if err != nil {
api.LogApiError("Couldn't encode response", err, userId, req)
return
}

res.Header().Set("Content-Type", "application/json")
_, err = res.Write(resJson)
if err != nil {
api.LogApiError("Couldn't write response", err, userId, req)
return
}

api.LogApiCall(userId, req)
}

func (r RoomApi) ServeCreateGame(baseUrl string, authWrapper auth.AuthWrapper) {
http.HandleFunc(fmt.Sprintf("%s/create", baseUrl), authWrapper(r.createGameHandler))
}
15 changes: 15 additions & 0 deletions internal/infra/api/roomapi/roomapi.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package roomapi

import (
"github.com/feelbeatapp/feelbeatserver/internal/lib/roomrepository"
)

type RoomApi struct {
roomRepo roomrepository.RoomRepository
}

func NewRoomApi(roomRepo roomrepository.RoomRepository) RoomApi {
return RoomApi{
roomRepo: roomRepo,
}
}
33 changes: 33 additions & 0 deletions internal/infra/auth/authorizethroughspotify.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package auth

import (
"net/http"
"strings"

"github.com/feelbeatapp/feelbeatserver/internal/infra/fblog"
"github.com/feelbeatapp/feelbeatserver/internal/lib/component"
"github.com/feelbeatapp/feelbeatserver/internal/thirdparty/spotify"
)

func AuthorizeThroughSpotify(handler func(string, http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(res http.ResponseWriter, req *http.Request) {
authHeader := req.Header.Get("Authorization")

splits := strings.Split(authHeader, "Bearer ")
if len(splits) != 2 {
http.Error(res, "Incorrect authorization format", http.StatusBadRequest)
fblog.Error(component.Auth, "Incorrect authorization format", "url", req.URL, "addr", req.RemoteAddr)
return
}
token := splits[1]

userId, err := spotify.GetUserId(token)
if err != nil {
http.Error(res, http.StatusText(http.StatusForbidden), http.StatusForbidden)
fblog.Error(component.Auth, "Access denied", "reason", err)
return
}

handler(userId, res, req)
}
}
5 changes: 5 additions & 0 deletions internal/infra/auth/authwrapper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package auth

import "net/http"

type AuthWrapper func(func(string, http.ResponseWriter, *http.Request)) func (http.ResponseWriter, *http.Request)
2 changes: 1 addition & 1 deletion internal/infra/ws/servewebsockets.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var upgrader = websocket.Upgrader{
},
}

func ServeWebsockets(hub *BasicHub, w http.ResponseWriter, r *http.Request) {
func ServeWebsockets(hub *WSHub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)

fblog.Info(component.WebSocket, "received new connection", "ip", r.RemoteAddr)
Expand Down
16 changes: 8 additions & 8 deletions internal/infra/ws/hub.go → internal/infra/ws/wshub.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import (
"github.com/feelbeatapp/feelbeatserver/internal/infra/fblog"
)

type BasicHub struct {
type WSHub struct {
clients map[HubClient]bool
broadcast chan ClientMessage
register chan HubClient
unregister chan HubClient
exit chan bool
}

func NewHub() *BasicHub {
return &BasicHub{
func NewHub() *WSHub {
return &WSHub{
clients: make(map[HubClient]bool),
broadcast: make(chan ClientMessage),
register: make(chan HubClient),
Expand All @@ -23,7 +23,7 @@ func NewHub() *BasicHub {
}
}

func (h *BasicHub) Run() {
func (h *WSHub) Run() {
defer func() {
for c := range h.clients {
c.Close()
Expand Down Expand Up @@ -55,18 +55,18 @@ func (h *BasicHub) Run() {
}
}

func (h *BasicHub) RegisterClient(client HubClient) {
func (h *WSHub) RegisterClient(client HubClient) {
h.register <- client
}

func (h *BasicHub) Broadcast(message ClientMessage) {
func (h *WSHub) Broadcast(message ClientMessage) {
h.broadcast <- message
}

func (h *BasicHub) UnregisterClient(client HubClient) {
func (h *WSHub) UnregisterClient(client HubClient) {
h.unregister <- client
}

func (h *BasicHub) Stop() {
func (h *WSHub) Stop() {
h.exit <- true
}
10 changes: 6 additions & 4 deletions internal/lib/component/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ package component

const (
FeelBeatServer = "FeelBeatServer"
Config = "config"
WebSocket = "websocket"
Client = "client"
Hub = "hub"
Config = "config"
WebSocket = "websocket"
Client = "client"
Hub = "hub"
Api = "api"
Auth = "auth"

AudioDownloadTask = "audiodownloadtask"
)
Expand Down
16 changes: 16 additions & 0 deletions internal/lib/feelbeaterror/errorcode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package feelbeaterror

import "net/http"

type ErrorCode string

const (
Default = "unexpected_error"
)

func StatusCode(code ErrorCode) int {
switch code {
default:
return http.StatusInternalServerError
}
}
12 changes: 12 additions & 0 deletions internal/lib/feelbeaterror/feelbeaterror.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package feelbeaterror

import "fmt"

type FeelBeatError struct {
DebugMessage string
UserMessage ErrorCode
}

func (e *FeelBeatError) Error() string {
return fmt.Sprintf("%s: %s", e.UserMessage, e.DebugMessage)
}
19 changes: 19 additions & 0 deletions internal/lib/room/room.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package room

type Room struct {
id string
ownerId string
settings RoomSettings
}

func NewRoom(id string, ownerId string, settings RoomSettings) Room {
return Room{
id: id,
settings: settings,
ownerId: ownerId,
}
}

func (r Room) Id() string {
return r.id
}
10 changes: 10 additions & 0 deletions internal/lib/room/roomsettings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package room

type RoomSettings struct {
MaxPlayers int `json:"maxPlayers"`
TurnCount int `json:"turnCount"`
TimePenaltyPerSecond int `json:"timePenaltyPerSecond"`
BasePoints int `json:"basePoints"`
IncorrectGuessPenalty int `json:"incorrectGuessPenalty"`
PlaylistId string `json:"playlistId"`
}
Loading
Loading