create intial db, models, websocket and architecture.
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"os"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type DB struct {
|
||||
*sql.DB
|
||||
}
|
||||
|
||||
func NewDB(path string) (*DB, error) {
|
||||
db, err := sql.Open("sqlite3", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
schema, err := os.ReadFile("../../migrations/schema.sql")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = db.Exec(string(schema))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &DB{db}, nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Message struct {
|
||||
ID int `json:"id"`
|
||||
RoomID string `json:"room_id"`
|
||||
User string `json:"user"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Room struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package websocket
|
||||
|
||||
type Hub struct {
|
||||
rooms map[string]*Room
|
||||
}
|
||||
|
||||
func NewHub() *Hub {
|
||||
return &Hub{
|
||||
rooms: make(map[string]*Room),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) GetOrCreateRoom(roomID string) *Room {
|
||||
if _, ok := h.rooms[roomID]; !ok {
|
||||
h.rooms[roomID] = NewRoom(roomID)
|
||||
}
|
||||
return h.rooms[roomID]
|
||||
}
|
||||
|
||||
func (h *Hub) CleanupRoom(roomID string) {
|
||||
room := h.rooms[roomID]
|
||||
if len(room.clients) == 0 {
|
||||
delete(h.rooms, roomID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package websocket
|
||||
|
||||
import "github.com/gorilla/websocket"
|
||||
|
||||
type Client struct {
|
||||
conn *websocket.Conn
|
||||
room *Room
|
||||
}
|
||||
|
||||
type Room struct {
|
||||
id string
|
||||
clients map[*Client]bool
|
||||
}
|
||||
|
||||
func NewRoom(id string) *Room {
|
||||
return &Room{
|
||||
id: id,
|
||||
clients: make(map[*Client]bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Room) Register(client *Client) {
|
||||
r.clients[client] = true
|
||||
}
|
||||
|
||||
func (r *Room) Unregister(client *Client) {
|
||||
delete(r.clients, client)
|
||||
client.conn.Close()
|
||||
}
|
||||
|
||||
func (r *Room) Broadcast(message []byte) {
|
||||
for client := range r.clients {
|
||||
err := client.conn.WriteMessage(websocket.TextMessage, message)
|
||||
if err != nil {
|
||||
r.Unregister(client)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user