2022-12-15 00:28:36 +01:00
|
|
|
package proto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2022-12-16 02:11:43 +01:00
|
|
|
"errors"
|
2022-12-15 00:28:36 +01:00
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Command(target string, request interface{}, response interface{}) error {
|
|
|
|
conn, err := net.Dial("tcp", target)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
if err = json.NewEncoder(conn).Encode(request); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return json.NewDecoder(conn).Decode(response)
|
|
|
|
}
|
|
|
|
|
|
|
|
func CommandTimeout(target string, request interface{}, response interface{}, timeout time.Duration) error {
|
2022-12-16 02:11:43 +01:00
|
|
|
responseChan := make(chan interface{})
|
|
|
|
errorChan := make(chan error)
|
2022-12-15 00:28:36 +01:00
|
|
|
|
2022-12-16 02:11:43 +01:00
|
|
|
go func() {
|
|
|
|
conn, err := net.DialTimeout("tcp", target, timeout)
|
|
|
|
if err != nil {
|
|
|
|
errorChan <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
if err = json.NewEncoder(conn).Encode(request); err != nil {
|
|
|
|
errorChan <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
responseChan <- json.NewDecoder(conn).Decode(response)
|
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case response = <-responseChan:
|
|
|
|
return nil
|
|
|
|
case err := <-errorChan:
|
2022-12-15 00:28:36 +01:00
|
|
|
return err
|
2022-12-16 02:11:43 +01:00
|
|
|
case <-time.After(timeout):
|
|
|
|
return errors.New("timout")
|
2022-12-15 00:28:36 +01:00
|
|
|
}
|
|
|
|
}
|