Skip to content

Commit

Permalink
feat(mux): implement hijacker interface in response writer (#74)
Browse files Browse the repository at this point in the history
  • Loading branch information
danibix95 authored Mar 28, 2024
1 parent 4e1ac18 commit 7ce8e8c
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
!.vscode/extensions.json
*.code-workspace

# Jetbrains
.idea

# Vim
# Swap
[._]*.s[a-v][a-z]
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## Unreleased

### Added

- introduce support for Hijacker interface in **mux** middleware response writer

## v4.1.0 - 16-10-2023

### Added
Expand Down
12 changes: 12 additions & 0 deletions middleware/mux/readableresponsewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
package mux

import (
"bufio"
"fmt"
"net"
"net/http"
)

Expand Down Expand Up @@ -60,3 +63,12 @@ func (r *readableResponseWriter) Flush() {
flusherWriter.Flush()
}
}

// Hijack func, calls the underlying ResponseWriter Hijack fn
func (r *readableResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacker, ok := r.Writer.(http.Hijacker); ok {
return hijacker.Hijack()
}

return nil, nil, fmt.Errorf("the Hijacker interface is not supported")
}
14 changes: 14 additions & 0 deletions middleware/mux/readableresponsewriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package mux

import (
"bufio"
"net"
"net/http"
"testing"
)
Expand All @@ -26,6 +28,7 @@ type ResponseWriterMock struct {
writeHeaderCalled bool
writeCalled bool
flushCalled bool
hijackCalled bool
}

func (r *ResponseWriterMock) Header() http.Header {
Expand All @@ -46,6 +49,12 @@ func (r *ResponseWriterMock) Flush() {
r.flushCalled = true
}

func (r *ResponseWriterMock) Hijack() (net.Conn, *bufio.ReadWriter, error) {
r.hijackCalled = true

return nil, nil, nil
}

func TestReadableResponseWriter(t *testing.T) {
mock := ResponseWriterMock{}
myw := readableResponseWriter{Writer: &mock}
Expand Down Expand Up @@ -73,4 +82,9 @@ func TestReadableResponseWriter(t *testing.T) {
if !mock.flushCalled {
t.Errorf("mock flush not called")
}

_, _, err = myw.Hijack()
if !mock.hijackCalled || err != nil {
t.Errorf("mock hijack not called successfully")
}
}

0 comments on commit 7ce8e8c

Please sign in to comment.