diff --git a/sdk/plugin/client.go b/sdk/plugin/client.go index bf29991434bd4036c8ff7d8f026585dea5618caa..2167035a7ad00b1d7cb0d446e9caccbb5a535dad 100644 --- a/sdk/plugin/client.go +++ b/sdk/plugin/client.go @@ -2,6 +2,7 @@ package plugin import ( "encoding/json" + "errors" "fmt" "io" "net/http" @@ -10,6 +11,7 @@ import ( "strings" "github.com/gin-gonic/gin" + "openeuler.org/PilotGo/plugin-sdk/utils" ) type Client struct { @@ -135,3 +137,54 @@ func (c *Client) MachineList() ([]*MachineNode, error) { } return result, nil } + +type Event struct { + ID int + MetaData interface{} +} + +type EventCallback func(e *Event) + +func (c *Client) ListenEvent(event Event, callback EventCallback) error { + url := c.Server + "/api/v1/pluginapi/listener" + data, err := utils.Request("PUT", url) + if err != nil { + return err + } + + resp := &struct { + Status string + Error string + }{} + if err := json.Unmarshal(data, resp); err != nil { + return err + } + if resp.Status != "ok" { + return errors.New(resp.Error) + } + + // TODO: register event handler here + return nil +} + +func (c *Client) UnListenEvent(listenerID string) error { + url := c.Server + "/api/v1/pluginapi/listener" + data, err := utils.Request("DELETE", url) + if err != nil { + return err + } + + resp := &struct { + Status string + Error string + }{} + if err := json.Unmarshal(data, resp); err != nil { + return err + } + if resp.Status != "ok" { + return errors.New(resp.Error) + } + + // TODO: unregister event handler here + return nil +} diff --git a/sdk/utils/request.go b/sdk/utils/request.go new file mode 100644 index 0000000000000000000000000000000000000000..fc8ea1c6cfa3697aab60ebfa97277d4b90e94409 --- /dev/null +++ b/sdk/utils/request.go @@ -0,0 +1,27 @@ +package utils + +import ( + "io" + "net/http" +) + +func Request(method, url string) ([]byte, error) { + req, err := http.NewRequest(method, url, nil) + if err != nil { + return nil, err + } + + hc := &http.Client{} + resp, err := hc.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + bs, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + return bs, nil +}