package main
import (
"context"
"encoding/json"
"net/http"
"github.com/go-mizu/mizu"
"github.com/go-mizu/mizu/live"
)
func main() {
server := live.New(live.Options{
OnAuth: func(ctx context.Context, r *http.Request) (any, error) {
userID := r.URL.Query().Get("user")
if userID == "" {
return nil, fmt.Errorf("user required")
}
return userID, nil
},
OnMessage: func(ctx context.Context, s *live.Session, topic string, data []byte) {
// Handle incoming messages
if topic == "subscribe" {
var req struct{ Topic string `json:"topic"` }
json.Unmarshal(data, &req)
server.Subscribe(s, req.Topic)
} else if topic == "chat" {
// Broadcast to all in chat
server.Publish("chat:general", data)
}
},
OnClose: func(s *live.Session, err error) {
log.Printf("Session %s closed: %v", s.ID(), err)
},
})
app := mizu.New()
app.Get("/ws", mizu.Compat(server.Handler()))
app.Listen(":8080")
}