Skip to content

Commit

Permalink
add a configurable timeout for responses received from the server
Browse files Browse the repository at this point in the history
if no response after the timeout, the request responds with an error

new option is `WithResponseTimeout(x time.Duration)`
  • Loading branch information
andreykaipov committed Nov 28, 2021
1 parent e229173 commit 8d28d35
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
11 changes: 10 additions & 1 deletion api/requests/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"time"

"github.com/gorilla/websocket"
uuid "github.com/nu7hatch/gouuid"
Expand All @@ -23,6 +24,9 @@ type Client struct {
// The backing websocket connection to the OBS websocket server.
Conn *websocket.Conn

// The time we're willing to wait to receive a response from the server.
ResponseTimeout time.Duration

// Raw JSON message responses from the websocker server.
IncomingResponses chan json.RawMessage

Expand Down Expand Up @@ -85,7 +89,12 @@ func (c *Client) SendRequest(params Params, response Response) error {
return err
}

msg := <-c.IncomingResponses
var msg json.RawMessage
select {
case msg = <-c.IncomingResponses:
case <-time.After(c.ResponseTimeout * time.Millisecond):
return fmt.Errorf("Timed out receiving response from server for request %q", params.GetRequestType())
}

// OBS websocket seems to return already pretty-printed JSON in its
// responses, so we compact the response to print it on just one line.
Expand Down
16 changes: 14 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"net/url"
"os"
"time"

"github.com/andreykaipov/goobs/api/events"
"github.com/andreykaipov/goobs/api/requests"
Expand Down Expand Up @@ -77,6 +78,15 @@ func WithRequestHeader(x http.Header) Option {
}
}

// WithResponseTimeout sets the time we're willing to wait to receive a response
// from the server for any request, before responding with an error. It's in
// milliseconds. The default timeout is 10 seconds.
func WithResponseTimeout(x time.Duration) Option {
return func(o *Client) {
o.ResponseTimeout = time.Duration(x)
}
}

type discard struct{}

func (o *discard) Printf(format string, v ...interface{}) {}
Expand All @@ -93,8 +103,10 @@ It also opens up a connection, so be sure to check the error.
*/
func New(host string, opts ...Option) (*Client, error) {
c := &Client{
Client: &requests.Client{},
host: host,
Client: &requests.Client{
ResponseTimeout: 10000,
},
host: host,
}

for _, opt := range opts {
Expand Down

0 comments on commit 8d28d35

Please sign in to comment.