aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHimbeerserverDE <himbeerserverde@gmail.com>2022-10-15 11:12:19 +0200
committerHimbeerserverDE <himbeerserverde@gmail.com>2022-10-15 11:12:19 +0200
commit2c7c1010bf080cf4c2aa457f2e99bd50dce5f50c (patch)
tree85136fd9444d9a7772bd2a175c57f38b827fd9ae
parentc55b7c61a2f0163b5e12401f4792b9223371c29f (diff)
add closing
-rw-r--r--client.go63
1 files changed, 56 insertions, 7 deletions
diff --git a/client.go b/client.go
index ec9b44e..2dec117 100644
--- a/client.go
+++ b/client.go
@@ -1,8 +1,10 @@
package inwx
import (
+ "net"
"net/http"
"net/http/cookiejar"
+ "sync/atomic"
"time"
"github.com/ybbus/jsonrpc/v3"
@@ -20,11 +22,16 @@ const requestTimeout = 30 * time.Second
// A Client is a session handle for the API.
type Client struct {
- rpcClient jsonrpc.RPCClient
- endpoint Endpoint
+ httpClient *http.Client
+ rpcClient jsonrpc.RPCClient
+ endpoint Endpoint
+
+ closed chan struct{}
+ closing uint32
+ err error
}
-func NewClient(endpoint Endpoint) (*Client, error) {
+func Login(endpoint Endpoint, user, passwd string) (*Client, error) {
jar, err := cookiejar.New(&cookiejar.Options{})
if err != nil {
return nil, err
@@ -35,12 +42,54 @@ func NewClient(endpoint Endpoint) (*Client, error) {
Timeout: requestTimeout,
}
+ rpcClient := jsonrpc.NewClientWithOpts(string(endpoint), &jsonrpc.RPCClientOpts{
+ HTTPClient: httpClient,
+ })
+
clt := &Client{
- rpcClient: jsonrpc.NewClientWithOpts(string(endpoint), &jsonrpc.RPCClientOpts{
- HTTPClient: httpClient,
- }),
- endpoint: endpoint,
+ httpClient: httpClient,
+ rpcClient: rpcClient,
+ endpoint: endpoint,
}
+ // TODO: login
+
return clt, nil
}
+
+// Closed returns a channel which is closed when the Client is closed.
+func (c *Client) Closed() <-chan struct{} { return c.closed }
+
+// WhyClosed returns the error that caused the Conn to be closed or nil
+// if the Conn was closed using the Close method.
+// WhyClosed returns nil if the Conn is not closed.
+func (c *Client) WhyClosed() error {
+ select {
+ case <-c.Closed():
+ return c.err
+ default:
+ return nil
+ }
+}
+
+// Close closes the Client. Any blocked Calls will return net.ErrClosed.
+func (c *Client) Close() error {
+ return c.closeLogout(nil)
+}
+
+func (c *Client) closeLogout(err error) error {
+ // TODO: logout
+
+ return c.close(err)
+}
+
+func (c *Client) close(err error) error {
+ if atomic.SwapUint32(&c.closing, 1) == 1 {
+ return net.ErrClosed
+ }
+
+ c.err = err
+ defer close(c.closed)
+
+ return nil
+}