69 lines
1.6 KiB
Go

package zabbixagent
import (
"context"
"fmt"
"golang.zabbix.com/sdk/errs"
"io"
"net/http"
"onvif-agent/config"
"onvif-agent/constant"
"strings"
)
// HandlerFunc describes the signature all metric handler functions must have.
type HandlerFunc func(
ctx context.Context,
metricParams map[string]string,
extraParams ...string,
) (any, error)
// Handler hold client and syscall implementation for request functions.
type Handler struct {
client *http.Client
}
func (h *Handler) GetAppVersion(_ context.Context, _ map[string]string, _ ...string) (any, error) {
return constant.AppVersion, nil
}
func (h *Handler) HTTPClient(ctx context.Context, params map[string]string, _ ...string) (any, error) {
method := params["method"]
if method == "" {
method = http.MethodGet
}
url := params["url"]
if !strings.HasPrefix(url, "http") {
url = fmt.Sprintf("http://127.0.0.1:%d%s", config.Config.App.Port, url)
}
body := params["body"]
req, err := http.NewRequestWithContext(ctx, method, url, strings.NewReader(body)) // TODO: if empty use http.NoBody
if err != nil {
return nil, errs.Wrapf(err, "failed to create request")
}
resp, err := h.client.Do(req)
if err != nil {
return nil, errs.Wrapf(err, "failed to send the request")
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errs.Wrapf(err, "failed to read the response")
}
return method + url + body + string(data), nil
}
// NewHandler creates a new handler with initialized clients for system and tcp calls.
func NewHandler() *Handler {
return &Handler{
client: http.DefaultClient,
}
}