|
| 1 | +package example |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + "github.com/robbyt/go-supervisor/runnables/httpserver" |
| 9 | +) |
| 10 | + |
| 11 | +// ResponseBuffer captures response data for transformation |
| 12 | +// |
| 13 | +// This is a simple example for demonstration purposes and is not intended for |
| 14 | +// production use. Limitations: |
| 15 | +// - Does not preserve optional HTTP interfaces (http.Hijacker, http.Flusher, http.Pusher) |
| 16 | +// - Not safe for concurrent writes from multiple goroutines within the same request |
| 17 | +// - No memory limits on buffered content |
| 18 | +// |
| 19 | +// Each request gets its own ResponseBuffer instance, so different requests won't |
| 20 | +// interfere with each other. |
| 21 | +type ResponseBuffer struct { |
| 22 | + buffer *bytes.Buffer |
| 23 | + headers http.Header |
| 24 | + status int |
| 25 | +} |
| 26 | + |
| 27 | +// NewResponseBuffer creates a new response buffer |
| 28 | +func NewResponseBuffer() *ResponseBuffer { |
| 29 | + return &ResponseBuffer{ |
| 30 | + buffer: new(bytes.Buffer), |
| 31 | + headers: make(http.Header), |
| 32 | + status: 0, // 0 means not set yet |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +// Header implements http.ResponseWriter |
| 37 | +func (rb *ResponseBuffer) Header() http.Header { |
| 38 | + return rb.headers |
| 39 | +} |
| 40 | + |
| 41 | +// Write implements http.ResponseWriter |
| 42 | +func (rb *ResponseBuffer) Write(data []byte) (int, error) { |
| 43 | + return rb.buffer.Write(data) |
| 44 | +} |
| 45 | + |
| 46 | +// WriteHeader implements http.ResponseWriter |
| 47 | +func (rb *ResponseBuffer) WriteHeader(statusCode int) { |
| 48 | + if rb.status == 0 { |
| 49 | + rb.status = statusCode |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// Status implements httpserver.ResponseWriter |
| 54 | +func (rb *ResponseBuffer) Status() int { |
| 55 | + if rb.status == 0 && rb.buffer.Len() > 0 { |
| 56 | + return http.StatusOK |
| 57 | + } |
| 58 | + return rb.status |
| 59 | +} |
| 60 | + |
| 61 | +// Written implements httpserver.ResponseWriter |
| 62 | +func (rb *ResponseBuffer) Written() bool { |
| 63 | + return rb.buffer.Len() > 0 || rb.status != 0 |
| 64 | +} |
| 65 | + |
| 66 | +// Size implements httpserver.ResponseWriter |
| 67 | +func (rb *ResponseBuffer) Size() int { |
| 68 | + return rb.buffer.Len() |
| 69 | +} |
| 70 | + |
| 71 | +// transformToJSON wraps non-JSON content in a JSON response |
| 72 | +func transformToJSON(data []byte) ([]byte, error) { |
| 73 | + // Use json.Valid for efficient validation without unmarshaling |
| 74 | + if json.Valid(data) { |
| 75 | + return data, nil // Valid JSON, return as-is |
| 76 | + } |
| 77 | + |
| 78 | + // If not valid JSON, wrap it |
| 79 | + response := map[string]string{ |
| 80 | + "response": string(data), |
| 81 | + } |
| 82 | + |
| 83 | + return json.Marshal(response) |
| 84 | +} |
| 85 | + |
| 86 | +// New creates a middleware that transforms all responses to JSON format. |
| 87 | +// Non-JSON responses are wrapped in {"response": "content"}. |
| 88 | +// Valid JSON responses are preserved as-is. |
| 89 | +func New() httpserver.HandlerFunc { |
| 90 | + return func(rp *httpserver.RequestProcessor) { |
| 91 | + // Store original writer before buffering |
| 92 | + originalWriter := rp.Writer() |
| 93 | + |
| 94 | + // Buffer the response to capture output |
| 95 | + buffer := NewResponseBuffer() |
| 96 | + rp.SetWriter(buffer) |
| 97 | + |
| 98 | + // Continue to next middleware/handler |
| 99 | + rp.Next() |
| 100 | + |
| 101 | + // RESPONSE PHASE: Transform response to JSON |
| 102 | + originalData := buffer.buffer.Bytes() |
| 103 | + statusCode := buffer.Status() |
| 104 | + if statusCode == 0 { |
| 105 | + statusCode = http.StatusOK |
| 106 | + } |
| 107 | + |
| 108 | + // Copy headers to original writer |
| 109 | + for key, values := range buffer.Header() { |
| 110 | + for _, value := range values { |
| 111 | + originalWriter.Header().Add(key, value) |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + // Check if this status code should have no body per HTTP spec |
| 116 | + // 204 No Content and 304 Not Modified MUST NOT have a message body |
| 117 | + if statusCode == http.StatusNoContent || statusCode == http.StatusNotModified { |
| 118 | + originalWriter.WriteHeader(statusCode) |
| 119 | + return |
| 120 | + } |
| 121 | + |
| 122 | + // Transform captured data to JSON |
| 123 | + if len(originalData) == 0 && buffer.status == 0 { |
| 124 | + return |
| 125 | + } |
| 126 | + |
| 127 | + // Transform to JSON if needed |
| 128 | + jsonData, err := transformToJSON(originalData) |
| 129 | + if err != nil { |
| 130 | + // Fallback: wrap error in JSON |
| 131 | + jsonData = []byte(`{"error":"Unable to encode response"}`) |
| 132 | + } |
| 133 | + |
| 134 | + // Ensure JSON content type |
| 135 | + originalWriter.Header().Set("Content-Type", "application/json") |
| 136 | + |
| 137 | + // Write status and transformed data |
| 138 | + originalWriter.WriteHeader(statusCode) |
| 139 | + if _, err := originalWriter.Write(jsonData); err != nil { |
| 140 | + // Response is already committed, cannot recover from write error |
| 141 | + return |
| 142 | + } |
| 143 | + } |
| 144 | +} |
0 commit comments