replaycli-go/api/cli.go

83 lines
1.5 KiB
Go
Raw Normal View History

2021-09-30 00:00:49 +00:00
package api
import (
2021-11-11 08:56:07 +00:00
"encoding/json"
"errors"
"github.com/nats-io/nats.go"
"go.digitalcircle.com.br/open/httpcli"
2021-10-31 09:37:05 +00:00
"go.digitalcircle.com.br/open/replaycli-go/ipcmux"
"go.digitalcircle.com.br/open/replaycli-go/util"
2021-11-11 08:56:07 +00:00
"log"
2021-09-30 00:00:49 +00:00
"os"
2021-11-11 08:56:07 +00:00
"time"
2021-09-30 00:00:49 +00:00
)
type ApiCli struct {
cli *httpcli.Cli
2021-09-30 00:00:49 +00:00
}
func (a *ApiCli) HttpCli() *httpcli.Cli {
return a.cli
2021-09-30 00:00:49 +00:00
}
func NewApiCli() *ApiCli {
ret := &ApiCli{cli: httpcli.C()}
ret.cli.SetBasePath(util.Addr())
2021-09-30 00:00:49 +00:00
apikey = os.Getenv("REPLAY_APIKEY")
ret.cli.AddHeader("X-API-KEY", apikey)
2021-09-30 00:00:49 +00:00
return ret
}
2021-10-31 09:37:05 +00:00
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
}
2021-11-11 08:56:07 +00:00
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()
}