Skip to content

Commit

Permalink
Fix broken ws upgrade introduced by using http.TimeoutHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
zale144 committed Apr 17, 2024
1 parent 25afe20 commit 93a6dc6
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
38 changes: 38 additions & 0 deletions rpc/middleware/timeout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package middleware

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

func NewTimeoutHandler(handler http.Handler, timeout time.Duration) http.Handler {
return &timeoutHandler{
handler: handler,
timeout: timeout,
}
}

type timeoutHandler struct {
handler http.Handler
timeout time.Duration
}

func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), h.timeout)
defer cancel()

r = r.WithContext(ctx)
h.handler.ServeHTTP(w, r)
}

func (h *timeoutHandler) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hijacker, ok := h.handler.(http.Hijacker)
if !ok {
return nil, nil, fmt.Errorf("the handler does not support Hijacker interface")
}
return hijacker.Hijack()
}
2 changes: 1 addition & 1 deletion rpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func (s *Server) startRPC() error {
middlewareClient := middleware.NewClient(*reg, s.Logger.With("module", "rpc/middleware"))
handler = middlewareClient.Handle(handler)
// Set a global timeout
handlerWithTimeout := http.TimeoutHandler(handler, s.timeout, "Server Timeout")
handlerWithTimeout := middleware.NewTimeoutHandler(handler, s.timeout)

// Start HTTP server
go func() {
Expand Down

0 comments on commit 93a6dc6

Please sign in to comment.