auto dial

mail@pastecode.io avatar
unknown
golang
3 years ago
889 B
1
Indexable
Never
package dial

import (
	"errors"
	"log"
	"net/rpc"
	"time"
)

type AutoDial struct {
	client *rpc.Client
	ready  bool
}

func NewAutoDial(network string, address string, checkMethod string) *AutoDial {
	a := &AutoDial{}
	go a.healthCheck(network, address, checkMethod)
	return a
}

func (a *AutoDial) healthCheck(network string, address string, checkMethod string) {
	for {
		client, err := rpc.Dial(network, address)

		if err == nil {
			a.client = client

			for {
				time.Sleep(time.Second)
				err := client.Call(checkMethod, struct{}{}, nil)

				if err == nil {
					a.ready = true
				} else {
					log.Println(err)
					break
				}
			}
		}

		a.ready = false
		time.Sleep(time.Second)
	}
}

func (a *AutoDial) Call(method string, args interface{}, reply interface{}) error {
	if a.ready {
		return a.client.Call(method, args, reply)
	}
	return errors.New("Dial is not ready")
}