Skip to content

Commit

Permalink
Improves timeout handling at http backend
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Apr 13, 2024
1 parent f8a73a8 commit ee03f41
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
33 changes: 29 additions & 4 deletions backend/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,51 @@ package backend
import (
"bytes"
"net/http"
"time"

"github.com/ksysoev/wasabi"
)

const defaultTimeout = 30 * time.Second

// HTTPBackend represents an HTTP backend for handling requests.
type HTTPBackend struct {
factory RequestFactory
client *http.Client
}

type httpBackendConfig struct {
defaultTimeout time.Duration
}

type HTTPBackendOption func(*httpBackendConfig)

// NewBackend creates a new instance of HTTPBackend with the given RequestFactory.
func NewBackend(factory RequestFactory) *HTTPBackend {
func NewBackend(factory RequestFactory, options ...HTTPBackendOption) *HTTPBackend {
httpBackendConfig := &httpBackendConfig{
defaultTimeout: defaultTimeout,
}

for _, option := range options {
option(httpBackendConfig)
}

return &HTTPBackend{
factory: factory,
client: &http.Client{},
client: &http.Client{
Timeout: httpBackendConfig.defaultTimeout,
},
}
}

// Handle handles the incoming connection and request.
// It sends the request to the backend server and returns the response to the connection.
func (b *HTTPBackend) Handle(conn wasabi.Connection, r wasabi.Request) error {
httpReq, err := b.factory(r)
if err != nil {
return err
}

httpReq = httpReq.WithContext(r.Context())

resp, err := b.client.Do(httpReq)
if err != nil {
return err
Expand All @@ -45,3 +64,9 @@ func (b *HTTPBackend) Handle(conn wasabi.Connection, r wasabi.Request) error {

return conn.Send(respBody.String())
}

func WithDefaultTimeout(timeout time.Duration) HTTPBackendOption {
return func(cfg *httpBackendConfig) {
cfg.defaultTimeout = timeout
}
}
3 changes: 3 additions & 0 deletions backend/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package backend

import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"testing"
Expand All @@ -19,6 +20,8 @@ func TestHTTPBackend_Handle(t *testing.T) {
mockConn := mocks.NewMockConnection(t)
mockReq := mocks.NewMockRequest(t)

mockReq.EXPECT().Context().Return(context.Background())

mockConn.EXPECT().Send("OK").Return(nil)
mockReq.EXPECT().Data().Return([]byte("test request"))

Expand Down

0 comments on commit ee03f41

Please sign in to comment.