kaandesu / go-chat

🚧 simple tcp chatroom server in go
1 stars 0 forks source link

[proposal] adopting the Elm architecture #5

Open kaandesu opened 1 month ago

kaandesu commented 1 month ago

This proposal suggests restructuring our chatroom server application using principles from the Elm Architecture for better modularity, maintainability, and testability.

Overview:

Model: Centralizes application state. Update: Handles events and updates state. View: Sends responses to clients (backend interpretation). Benefits:

Example Changes:

Model:

type Model struct {
    users        map[string]*User
    childServers map[string]*Server
    msgch        chan Message
    quitch       chan struct{}
}

Update:

type Event struct {
    Type    string
    User    *User
    Message string
}

func update(model *Model, event Event) {
    switch event.Type {
    case "new_user":
        handleNewUser(model, event.User)
    case "message":
        handleNewMessage(model, event.User, event.Message)
    case "disconnect":
        handleUserDisconnect(model, event.User)
    }
}

View:

func sendWelcomeMessage(user *User) {
    user.conn.Write([]byte("Welcome " + user.username + "\n"))
}

func broadcastMessage(model *Model, message string) {
    for _, user := range model.users {
        user.conn.Write([]byte(message))
    }
}
kaandesu commented 1 month ago

yes I am proposing this to myself, go away