diff options
author | Julien Dessaux | 2025-01-03 00:54:15 +0100 |
---|---|---|
committer | Julien Dessaux | 2025-01-03 00:54:15 +0100 |
commit | c18d03d4049e7fe2e032ba448e88a44671dfdbeb (patch) | |
tree | 09cfe305f3bb468b9a3a750c92c9b54e574a21ab /pkg/middlewares/logger/body_writer.go | |
parent | feat(tfstated): bootstrap webui listening on a second port (diff) | |
download | tfstated-c18d03d4049e7fe2e032ba448e88a44671dfdbeb.tar.gz tfstated-c18d03d4049e7fe2e032ba448e88a44671dfdbeb.tar.bz2 tfstated-c18d03d4049e7fe2e032ba448e88a44671dfdbeb.zip |
chore(tfstated): refactor middlewares
Diffstat (limited to 'pkg/middlewares/logger/body_writer.go')
-rw-r--r-- | pkg/middlewares/logger/body_writer.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/pkg/middlewares/logger/body_writer.go b/pkg/middlewares/logger/body_writer.go new file mode 100644 index 0000000..f57a03e --- /dev/null +++ b/pkg/middlewares/logger/body_writer.go @@ -0,0 +1,65 @@ +package logger + +import ( + "bufio" + "bytes" + "errors" + "net" + "net/http" +) + +type bodyWriter struct { + http.ResponseWriter + body *bytes.Buffer + maxSize int + bytes int + status int +} + +func newBodyWriter(writer http.ResponseWriter, recordBody bool) *bodyWriter { + var body *bytes.Buffer + if recordBody { + body = bytes.NewBufferString("") + } + return &bodyWriter{ + body: body, + maxSize: 64000, + ResponseWriter: writer, + status: http.StatusNotImplemented, + } +} + +// implements http.ResponseWriter +func (w *bodyWriter) Write(b []byte) (int, error) { + if w.body != nil { + if w.body.Len()+len(b) > w.maxSize { + w.body.Write(b[:w.maxSize-w.body.Len()]) + } else { + w.body.Write(b) + } + } + + w.bytes += len(b) + return w.ResponseWriter.Write(b) +} + +// implements http.ResponseWriter +func (w *bodyWriter) WriteHeader(code int) { + w.status = code + w.ResponseWriter.WriteHeader(code) +} + +// implements http.Flusher +func (w *bodyWriter) Flush() { + if f, ok := w.ResponseWriter.(http.Flusher); ok { + f.Flush() + } +} + +// implements http.Hijacker +func (w *bodyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + if hi, ok := w.ResponseWriter.(http.Hijacker); ok { + return hi.Hijack() + } + return nil, nil, errors.New("Hijack not supported") +} |