Skip to content
This repository has been archived by the owner on Nov 21, 2023. It is now read-only.

Commit

Permalink
v0.4.2, client Options and timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
superisaac committed Apr 23, 2023
1 parent 95e6f80 commit 4527bb2
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 8 deletions.
4 changes: 2 additions & 2 deletions http/client_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ import (
// supported url schemes: the HTTP/1.1 client, the websocket based
// client and HTTP2 base client, the latter two types are streaming
// clients which can accept server push messages.
func NewClient(serverUrl string) (Client, error) {
func NewClient(serverUrl string, optlist ...ClientOptions) (Client, error) {
u, err := url.Parse(serverUrl)
if err != nil {
return nil, errors.Wrap(err, "url.Parse")
}
switch u.Scheme {
case "http", "https":
// HTTP/1.1 client
return NewH1Client(u), nil
return NewH1Client(u, optlist...), nil
case "ws", "wss":
// Websocket client
return NewWSClient(u), nil
Expand Down
22 changes: 16 additions & 6 deletions http/h1_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,26 @@ import (
)

type H1Client struct {
serverUrl *url.URL
extraHeader http.Header
httpClient *http.Client
serverUrl *url.URL
extraHeader http.Header
httpClient *http.Client
clientOptions ClientOptions

connectOnce sync.Once

clientTLS *tls.Config
}

func NewH1Client(serverUrl *url.URL) *H1Client {
func NewH1Client(serverUrl *url.URL, optlist ...ClientOptions) *H1Client {
if serverUrl.Scheme != "http" && serverUrl.Scheme != "https" {
log.Panicf("server url %s is not http", serverUrl)
}
return &H1Client{serverUrl: serverUrl}

clientOptions := ClientOptions{}
if len(optlist) > 0 {
clientOptions = optlist[0]
}
return &H1Client{serverUrl: serverUrl, clientOptions: clientOptions}
}

func (self *H1Client) ServerURL() *url.URL {
Expand All @@ -37,6 +43,10 @@ func (self *H1Client) ServerURL() *url.URL {

func (self *H1Client) connect() {
self.connectOnce.Do(func() {
timeout := self.clientOptions.Timeout
if timeout <= 0 {
timeout = 5
}
tr := &http.Transport{
MaxIdleConns: 30,
MaxIdleConnsPerHost: 10,
Expand All @@ -47,7 +57,7 @@ func (self *H1Client) connect() {
}
self.httpClient = &http.Client{
Transport: tr,
Timeout: 5 * time.Second,
Timeout: time.Duration(timeout) * time.Second,
}
})
}
Expand Down
5 changes: 5 additions & 0 deletions http/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import (
"net/url"
)

type ClientOptions struct {
// client request timeout
Timeout int `json:"timeout" yaml:"timeout"`
}

// Client is an abstract interface a client type must implement
type Client interface {
// Returns the server URL
Expand Down

0 comments on commit 4527bb2

Please sign in to comment.