TuChat
A self-hosted chat server and terminal client in Go, with accounts and rooms over a JSON protocol on raw TCP.
- Go
- TCP
- Bubble Tea
- Docker
TuChat | #general (localhost:8080) Users: 4
• guest
• anthony
• ethan
• lucas
Tab to switch tabs
○ Click the screen or press i to type.
Simulated in your browser, with the real client's layout, keys, and messages. Try /help, /nick, or /join golang. The password for ops is demo.
tuchat.go
How it works
The server accepts raw TCP connections and exchanges newline-delimited JSON. The terminal client is a Bubble Tea program, and both sides import the same protocol package, so there is one definition of a message.
A slow client can't stall a room
Each connection has its own writer goroutine, fed by a channel that holds 64 messages. Send never blocks: if a client's outbox is full, the server disconnects that client instead of making everyone else wait.
func (c *Client) Send(msg protocol.Message) error {
select {
case <-c.done:
return errors.New("connection closed")
default:
}
select {
case c.outbox <- msg:
return nil
default:
go c.stop()
return errors.New("outbox full; client evicted")
}
}Short-lived locks
The server, each room, and each user guard their own state with a mutex. A broadcast copies the member list under a read lock and releases it before sending, so the room isn't locked while messages are being queued.
Accounts and rooms
Account and room passwords are hashed with bcrypt. Logging in allows three attempts within two minutes. Whoever creates a room owns it, and can set a password or promote admins, who can set the topic and kick people.
Restarts and shutdown
Settings are written to a temporary file and renamed into place, so an interrupted write doesn't leave a half-written config. Each room keeps an append-only log that /history reads back. On shutdown the server stops accepting connections, tells everyone, and waits for its goroutines to finish.
architecture
- Bubble Tea client
- JSON over TCP
- Connection goroutine
- Room broadcast
- Per-client outbox
- Writer goroutine
highlights
- A bounded outbox per client, so one slow connection can't block a room
- Bcrypt-hashed accounts and password-protected rooms
- Dockerized server with graceful shutdown