This guide explains how to add new communication endpoints for both REST API and WebSocket in the codebase.
- Define the Request/Response Types
// In shared/api/types.go or a new type file
type NewFeatureRequest struct {
// Add request fields
Field string `json:"field"`
}
type NewFeatureResponse struct {
// Add response fields
Result string `json:"result"`
}
- Create a New Route
// In shared/api/routes.go
var NewFeatureRoute = http.NewRoute[NewFeatureRequest, NewFeatureResponse](
"/api/new-feature",
http.MethodPost,
)
- Implement the Handler (Server-side)
// In your handler file
func HandleNewFeature(req NewFeatureRequest) (NewFeatureResponse, error) {
// Implement your handler logic
return NewFeatureResponse{
Result: "processed",
}, nil
}
- Add Client-side Implementation
// In shared/http/client.go or your frontend code
func CallNewFeature(req NewFeatureRequest) (NewFeatureResponse, error) {
return client.Do(NewFeatureRoute, req)
}
- Define the Message Type
// In shared/ws/messages.go
const (
// Add your new message type
TypeNewFeature MessageType = "NEW_FEATURE"
)
- Create the Payload Structure
// In shared/ws/messages.go
type NewFeaturePayload struct {
// Define your payload fields
Data string `json:"data"`
UserID string `json:"user_id"`
}
- Handle the Message (Server-side)
// In your handler (e.g., internal/actors/client.go)
switch msg.Type {
case ws.TypeNewFeature:
payload := msg.Payload.(NewFeaturePayload)
// Handle the new feature message
}
- Send Messages (Client-side)
// In your frontend code
connection.Send(ws.Message{
Type: ws.TypeNewFeature,
Payload: NewFeaturePayload{
Data: "example",
UserID: "user123",
},
})
- Type Safety: Always use strongly typed structures for both REST and WebSocket communications.
- Documentation: Add comments explaining the purpose of new message types and payloads.
- Validation: Implement proper validation for all incoming data.
- Error Handling: Define appropriate error responses and handle them gracefully.
- Testing: Add tests for new endpoints and message handlers.
- REST endpoints use the
Route[Req, Res]
generic type for type safety - WebSocket messages follow the
Message
structure with specific payload types - All WebSocket message types are defined as constants
- Each message type has its own payload structure