Skip to content

Commit

Permalink
added REST API with POST & GET
Browse files Browse the repository at this point in the history
  • Loading branch information
Louuie committed Dec 24, 2024
1 parent d87ea88 commit 88cdbfc
Show file tree
Hide file tree
Showing 9 changed files with 228 additions and 5 deletions.
64 changes: 64 additions & 0 deletions fiber/db/postgres.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package db

import (
"database/sql"
"errors"
"fmt"
"os"

"github.com/lib/pq"
_ "github.com/lib/pq"
)

type Room struct {
UUID string `json:"uuid,omitempty"`
Room_Number string `json:"room_number,omitempty"`
}

func ConnectToDB() (*sql.DB, error) {
fmt.Println(os.Getenv("GO_CHAT_DB"))
db, err := sql.Open("postgres", os.Getenv("GO_CHAT_DB"))
if err != nil {
return nil, err
}
ping := db.Ping()
if ping != nil {
return nil, ping
}
return db, nil
}
func CreateTable(db *sql.DB) error {
_, err := db.Exec("CREATE TABLE IF NOT EXISTS rooms (UUID VARCHAR NOT NULL, room_number INTEGER NOT NULL, PRIMARY KEY(UUID))")
if err, ok := err.(*pq.Error); ok {
return errors.New(err.Code.Name())
}
return nil
}
func CreateRoom(db *sql.DB, UUID string) (string, int, error) {
var room_nuber = 1
_, err := db.Exec("INSERT into rooms VALUES ($1, $2)", UUID, room_nuber)
if err, ok := err.(*pq.Error); ok {
// 23505: unique_violation
if err.Code.Name() == "unique_violation" {
return "", 0, errors.New("that song is already in the queue")
}
}
return UUID, room_nuber, nil
}

func GetAllRooms(db *sql.DB) (*[]Room, error) {
roomsQuery, err := db.Query("SELECT * FROM rooms")
if err, ok := err.(*pq.Error); ok {
return nil, err
}
rooms := make([]Room, 0)
for roomsQuery.Next() {
room := Room{}
err := roomsQuery.Scan(&room.UUID, &room.Room_Number)
if err != nil {
return nil, err
}
rooms = append(rooms, room)
}
return &rooms, nil
}
46 changes: 46 additions & 0 deletions fiber/handlers/create_room.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package handlers

import (
"gochat/fiber/db"

"github.com/gofiber/fiber/v2"
"golang.org/x/exp/rand"
)

func CreateRoom(c *fiber.Ctx) error {
// Generate random UUIDs
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
generated_uuid := RandStringBytes(6, letterBytes)

database, dbConnErr := db.ConnectToDB()
if dbConnErr != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": dbConnErr.Error(),
})
}
dbCreateTableErr := db.CreateTable(database)
if dbCreateTableErr != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": dbCreateTableErr.Error(),
})
}
UUID, room_number, roomCreateErr := db.CreateRoom(database, generated_uuid)
if roomCreateErr != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": roomCreateErr.Error(),
})
}
database.Close()
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"uuid": UUID,
"room_number": room_number,
"status": "Good!",
})
}
func RandStringBytes(n int, letterBytes string) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
25 changes: 25 additions & 0 deletions fiber/handlers/fetch_rooms.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package handlers

import (
"gochat/fiber/db"

"github.com/gofiber/fiber/v2"
)

func FetchAllRooms(c *fiber.Ctx) error {
database, databaseConnErr := db.ConnectToDB()
if databaseConnErr != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": databaseConnErr.Error(),
})
}
rooms, databaseGetAllRoomErr := db.GetAllRooms(database)
if databaseGetAllRoomErr != nil {
return c.Status(fiber.ErrBadRequest.Code).JSON(fiber.Map{
"error": databaseGetAllRoomErr.Error(),
})
}
return c.Status(fiber.StatusOK).JSON(fiber.Map{
"rooms": rooms,
})
}
22 changes: 22 additions & 0 deletions fiber/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package fiber

import (
"gochat/fiber/handlers"
"log"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
)

func StartServer() {
app := fiber.New()
app.Use(cors.New(cors.Config{
AllowOrigins: "*",
AllowHeaders: "Access-Control-Allow-Origin, Content-Type, Origin, Accept",
}), logger.New())

app.Post("/create-room", handlers.CreateRoom)
app.Get("/fetch-rooms", handlers.FetchAllRooms)
log.Fatal(app.Listen(":" + "5050"))
}
24 changes: 23 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
module gochat

go 1.21
go 1.22.0

toolchain go1.23.3

require github.com/gorilla/websocket v1.5.3 // direct

require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/gofiber/fiber/v2 v2.52.5 // direct
github.com/google/uuid v1.5.0 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasthttp v1.51.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/sys v0.15.0 // indirect
)

require (
github.com/lib/pq v1.10.9 // indirect
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 // indirect
)
31 changes: 31 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,2 +1,33 @@
github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs=
github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo=
github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.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/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.51.0 h1:8b30A5JlZ6C7AS81RsWjYMQmrZG6feChmgAolCl1SqA=
github.com/valyala/fasthttp v1.51.0/go.mod h1:oI2XroL+lI7vdXyYoQk03bXBThfFl2cVdIA3Xl7cH8g=
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67 h1:1UoZQm6f0P/ZO0w1Ri+f+ifG/gXhegadRdwBIXEFWDo=
golang.org/x/exp v0.0.0-20241217172543-b2144cdd0a67/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
6 changes: 5 additions & 1 deletion go_chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"gochat/fiber"
"gochat/page"
"gochat/ws"
)
Expand All @@ -10,8 +11,11 @@ func main() {
// Start WebSocket server
ws.StartServer(messageHandler)

// Start fiber server
fiber.StartServer()

// Start the static HTML Page
page.Start()
page.StartPage()

// Block main thread to keep server running
select {}
Expand Down
2 changes: 1 addition & 1 deletion page/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,6 @@ func main() {
http.ListenAndServe(":3030", nil)
}

func Start() {
func StartPage() {
main()
}
13 changes: 11 additions & 2 deletions ws/web_socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ var upgrader = websocket.Upgrader{

type Server struct {
clients map[*websocket.Conn]bool
UUID map[string]string
handleMessage func(message []byte)
}

func StartServer(handleMessage func(message []byte)) *Server {
server := Server{
make(map[*websocket.Conn]bool),
make(map[string]string),
handleMessage,
}
http.HandleFunc("/ws", server.echo)
Expand All @@ -29,18 +31,25 @@ func StartServer(handleMessage func(message []byte)) *Server {
}

func (server *Server) echo(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatalln(err)
}
var chatUUID = "42fsqg-kl42fe"
server.UUID[chatUUID] = "1"
server.clients[conn] = true
for {
mt, msg, err := conn.ReadMessage()
if err != nil || mt == websocket.CloseMessage {
log.Fatalln(err)
break
}
go server.handleMessage(msg)
go server.WriteMessage(msg)
}
delete(server.clients, conn)
conn.Close()
delete(server.clients, conn)
delete(server.UUID, chatUUID)
}

func (server *Server) WriteMessage(message []byte) {
Expand Down

0 comments on commit 88cdbfc

Please sign in to comment.