Skip to content

sse oapi-codegen strict gin #48

@KevinNitroG

Description

@KevinNitroG

Ref: oapi-codegen/oapi-codegen#1764

AI suggest

// SSEWrapper wraps your generated models and handles the "Flushing" 
// bug in oapi-codegen's strict server.
type SSEWrapper[T any] struct {
    Events <-chan T
}

// Read satisfies the io.Reader interface but isn't used.
func (s SSEWrapper[T]) Read(p []byte) (n int, err error) { return 0, io.EOF }

// WriteTo is the "Magic" that oapi-codegen's io.Copy will trigger.
func (s SSEWrapper[T]) WriteTo(w io.Writer) (int64, error) {
    f, ok := w.(http.Flusher)
    if !ok {
        return 0, errors.New("streaming unsupported")
    }

    for event := range s.Events {
        // We use JSON for your 4-5 models
        data, _ := json.Marshal(event)
        
        // SSE format: data: <json>\n\n
        _, err := fmt.Fprintf(w, "data: %s\n\n", string(data))
        if err != nil {
            return 0, err
        }
        
        f.Flush() // <--- This fixes Issue #1764
    }
    return 0, nil
func (s *Server) GetWorkspaceUpdates(ctx context.Context, request GetWorkspaceUpdatesRequestObject) (GetWorkspaceUpdatesResponseObject, error) {
    // 1. Create a channel for your generated models
    // (e.g., your Union type or specific Event structs)
    eventChan := make(chan MyGeneratedEventModel)

    // 2. Start your logic to feed the channel (e.g., from Redis)
    go s.streamEventsFromRedis(request.WorkspaceId, eventChan)

    // 3. Return the wrapper
    return GetWorkspaceUpdates200TextEventStreamResponse{
        Body: SSEWrapper[MyGeneratedEventModel]{Events: eventChan},
    }, nil
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions