public-ip-tracker/tracker/unixsender/unixsender.go

67 lines
1.5 KiB
Go
Raw Permalink Normal View History

package unixsender
import (
"bytes"
"context"
"fmt"
"net"
"net/http"
"git.faercol.me/faercol/public-ip-tracker/tracker/config"
"git.faercol.me/faercol/public-ip-tracker/tracker/logger"
"github.com/sirupsen/logrus"
)
const method = http.MethodPost
const baseURL = "http://unix/"
type UnixSender struct {
logger *logrus.Logger
ctx context.Context
cancel context.CancelFunc
httpClt *http.Client
}
func (s *UnixSender) SendMessage(message string) error {
s.logger.Debug("Sending message to unix sock")
body := bytes.NewBufferString(message)
req, err := http.NewRequestWithContext(s.ctx, method, baseURL, body)
if err != nil {
return fmt.Errorf("failed to prepare request: %w", err)
}
resp, err := s.httpClt.Do(req)
if err != nil {
return fmt.Errorf("failed to run query: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("invalid returncode %d", resp.StatusCode)
}
return nil
}
func New(ctx context.Context, config *config.Config) (*UnixSender, error) {
subCtx, cancel := context.WithCancel(ctx)
logger.L.Infof("Creating Unix exporter to sock %q", config.Export.UnixSock)
httpClt := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dialer := net.Dialer{}
return dialer.DialContext(ctx, "unix", config.Export.UnixSock)
},
},
}
return &UnixSender{
ctx: subCtx,
cancel: cancel,
httpClt: &httpClt,
logger: &logger.L,
}, nil
}