func (c *Client) initWebsocket(stats []StatType) (chan Stat, func() error, error) {
	wsURL := *c.apiURL
	wsURL.Scheme = "wss"
	wsURL.Path = "/ws/stats"
	cfg, err := websocket.NewConfig(wsURL.String(), c.apiURL.String())
	if err != nil {
		return nil, nil, err
	}
	if tr, ok := c.client.Transport.(*http.Transport); ok {
		cfg.TlsConfig = tr.TLSClientConfig
	}
	var sessionID string
	for _, c := range c.client.Jar.Cookies(c.apiURL) {
		if c.Name == sessionCookie {
			sessionID = c.Value
			break
		}
	}
	wsc, err := websocket.DialConfig(cfg)
	if err != nil {
		return nil, nil, err
	}
	wsCodec := &websocket.Codec{
		Marshal:   wsMarshal,
		Unmarshal: wsUnmarshal,
	}
	wsns := make([]wsName, 0, len(stats))
	for _, stat := range stats {
		wsns = append(wsns, wsName{Name: stat})
	}
	sub := &wsRequest{
		Subscribe: wsns,
		SessionID: sessionID,
	}
	if err := wsCodec.Send(wsc, sub); err != nil {
		return nil, nil, err
	}
	statC := make(chan Stat)
	doneC := make(chan struct{})
	wg := new(sync.WaitGroup)
	done := statsDone(wg, sub, wsCodec, wsc, doneC)
	wg.Add(1)
	go collectStats(wg, wsCodec, wsc, statC, doneC)
	return statC, done, nil
}
initWebsocket initializes the websocket used for Client.Stats, and provides
a closure which can be used to clean it up.
package edgemax
import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
	"time"
	"golang.org/x/net/websocket"
)
func (c *Client) Stats(stats ...StatType) (statC chan Stat, done func() error, err error) {
	if stats == nil {
		stats = []StatType{
			StatTypeDPIStats,
			StatTypeInterfaces,
			StatTypeSystemStats,
		}
	}
	doneC := make(chan struct{})
	errC := make(chan error)
	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		defer func() {
			close(errC)
			wg.Done()
		}()
		if err := c.keepalive(doneC); err != nil {
			errC <- err
		}
	}()
	statC, wsDone, err := c.initWebsocket(stats)
	if err != nil {
		return nil, nil, err
	}
	done = func() error {
		close(doneC)
		wg.Wait()
		if err := <-errC; err != nil {
			return err
		}
		if err := wsDone(); err != nil {
			return err
		}
		close(statC)
		return nil
	}
	return statC, done, nil
}
const (
	sessionCookie = "PHPSESSID"
)