package api import ( "encoding/json" "errors" "github.com/nats-io/nats.go" "go.digitalcircle.com.br/open/httpcli" "go.digitalcircle.com.br/open/replaycli-go/ipcmux" "go.digitalcircle.com.br/open/replaycli-go/util" "log" "os" "time" ) type ApiCli struct { cli *httpcli.Cli } func (a *ApiCli) HttpCli() *httpcli.Cli { return a.cli } func NewApiCli() *ApiCli { ret := &ApiCli{cli: httpcli.C()} ret.cli.SetBasePath(util.Addr()) apikey = os.Getenv("REPLAY_APIKEY") ret.cli.AddHeader("X-API-KEY", apikey) return ret } func NewApiIPCCli() *ApiCli { ret := &ApiCli{cli: httpcli.NewCli()} ret.cli.SetCli(ipcmux.NewClient()) apikey = os.Getenv("REPLAY_APIKEY") ret.cli.AddHeader("X-API-KEY", apikey) return ret } var nc *nats.Conn func Call(s string, in interface{}, out interface{}) error { if nc == nil { var err error apikey = os.Getenv("REPLAY_APIKEY") if apikey == "" { log.Printf("Connecting to NATS Server w/o TK.") nc, err = nats.Connect(nats.DefaultURL) } else { log.Printf("Connecting to NATS Server w TK: " + apikey) nc, err = nats.Connect(nats.DefaultURL, nats.Token(apikey)) } if err != nil { return err } } bs, err := json.Marshal(in) if err != nil { return err } msg, err := nc.Request(s, bs, time.Minute) if err != nil { return err } err = json.Unmarshal(msg.Data, out) if err != nil { out = bs return err } errstr := msg.Header.Get("ERR") if errstr != "" { return errors.New(errstr) } return nil } func Close() error { return nc.Drain() }