forked from speakeasy-api/speakeasy-auth-test-service
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconnection_error_injector.go
More file actions
42 lines (32 loc) · 1018 Bytes
/
connection_error_injector.go
File metadata and controls
42 lines (32 loc) · 1018 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package middleware
import (
"net"
"net/http"
"github.com/lingrino/go-fault"
)
var _ fault.Injector = (*ConnectionErrorInjector)(nil)
// Injects a connection error by closing the connection immediately.
// This simulates a connection reset or close error.
type ConnectionErrorInjector struct {
// Enable to set SO_LINGER to 0 before closing, which will cause a TCP RST
// packet on most platforms when closing.
Reset bool
}
func (i *ConnectionErrorInjector) Handler(_ http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hijacker, ok := w.(http.Hijacker)
if !ok {
http.Error(w, "connection hijacking not supported", http.StatusInternalServerError)
return
}
conn, _, err := hijacker.Hijack()
if err != nil {
http.Error(w, "failed to hijack connection", http.StatusInternalServerError)
return
}
if tcpConn, ok := conn.(*net.TCPConn); ok && i.Reset {
_ = tcpConn.SetLinger(0) // Best effort RST on close
}
conn.Close()
})
}