| 1 |
/* |
| 2 |
Copyright 2024 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package responsewriter |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"net/http" |
| 22 |
) |
| 23 |
|
| 24 |
// inMemoryResponseWriter is a http.Writer that keep the response in memory. |
| 25 |
type inMemoryResponseWriter struct { |
| 26 |
writeHeaderCalled bool |
| 27 |
header http.Header |
| 28 |
respCode int |
| 29 |
data []byte |
| 30 |
} |
| 31 |
|
| 32 |
func NewInMemoryResponseWriter() *inMemoryResponseWriter { |
| 33 |
return &inMemoryResponseWriter{header: http.Header{}} |
| 34 |
} |
| 35 |
|
| 36 |
func (r *inMemoryResponseWriter) Header() http.Header { |
| 37 |
return r.header |
| 38 |
} |
| 39 |
|
| 40 |
func (r *inMemoryResponseWriter) RespCode() int { |
| 41 |
return r.respCode |
| 42 |
} |
| 43 |
|
| 44 |
func (r *inMemoryResponseWriter) Data() []byte { |
| 45 |
return r.data |
| 46 |
} |
| 47 |
|
| 48 |
func (r *inMemoryResponseWriter) WriteHeader(code int) { |
| 49 |
r.writeHeaderCalled = true |
| 50 |
r.respCode = code |
| 51 |
} |
| 52 |
|
| 53 |
func (r *inMemoryResponseWriter) Write(in []byte) (int, error) { |
| 54 |
if !r.writeHeaderCalled { |
| 55 |
r.WriteHeader(http.StatusOK) |
| 56 |
} |
| 57 |
r.data = append(r.data, in...) |
| 58 |
return len(in), nil |
| 59 |
} |
| 60 |
|
| 61 |
func (r *inMemoryResponseWriter) String() string { |
| 62 |
s := fmt.Sprintf("ResponseCode: %d", r.respCode) |
| 63 |
if r.data != nil { |
| 64 |
s += fmt.Sprintf(", Body: %s", string(r.data)) |
| 65 |
} |
| 66 |
if r.header != nil { |
| 67 |
s += fmt.Sprintf(", Header: %s", r.header) |
| 68 |
} |
| 69 |
return s |
| 70 |
} |