From 3761f85966a554cb750809da21995354fb9f9ceb Mon Sep 17 00:00:00 2001 From: Julio Capote Date: Sun, 18 Dec 2022 22:00:36 -0500 Subject: uncommit --- cgi/servers.go | 39 ++++++++++++++++++++++++++++----------- 1 file changed, 28 insertions(+), 11 deletions(-) (limited to 'cgi') diff --git a/cgi/servers.go b/cgi/servers.go index 0f23aac..84d6ffe 100644 --- a/cgi/servers.go +++ b/cgi/servers.go @@ -3,7 +3,7 @@ package cgi import ( "context" "fmt" - "io" + "io/ioutil" "net" "net/http" "net/http/cgi" @@ -12,12 +12,17 @@ import ( "time" "git.capotej.com/capotej/communique/config" + "github.com/dgraph-io/badger/v3" + "go.uber.org/zap" ) -type Servers struct{} +type Servers struct { + log *zap.SugaredLogger + db *badger.DB +} -func NewServers() *Servers { - return &Servers{} +func NewServers(log *zap.SugaredLogger, db *badger.DB) *Servers { + return &Servers{log: log, db: db} } // Start iterates over all Handlers and starts an internal CGI server for each one @@ -33,7 +38,7 @@ func (s *Servers) Start(cfg config.Config) { }(handler) go func(aHandler config.Handler) { defer wg.Done() - startTicker(aHandler) + startTicker(aHandler, s.db, s.log) }(handler) } wg.Wait() @@ -55,23 +60,32 @@ func startCGIServer(h config.Handler) { server.Serve(unixListener) } -func startTicker(h config.Handler) { +func startTicker(h config.Handler, db *badger.DB, log *zap.SugaredLogger) { // TODO add config for this - ticker := time.NewTicker(5 * time.Second) + ticker := time.NewTicker(h.Interval) done := make(chan bool) func() { for { select { case <-done: return - case _ = <-ticker.C: - tick(h) + case t := <-ticker.C: + output := tick(h) + keyName := fmt.Sprintf("outbox:%s:%d", h.Name, t.Unix()) + err := db.Update(func(txn *badger.Txn) error { + e := badger.NewEntry([]byte(keyName), output) + log.With("name", "ticker").Infof("writing '%s' to %s", output, keyName) + return txn.SetEntry(e) + }) + if err != nil { + log.Error(err) + } } } }() } -func tick(h config.Handler) { +func tick(h config.Handler) []byte { sock := fmt.Sprintf("%s.sock", h.Name) httpc := http.Client{ Transport: &http.Transport{ @@ -86,5 +100,8 @@ func tick(h config.Handler) { if err != nil { panic(err) } - io.Copy(os.Stdout, response.Body) + + body, err := ioutil.ReadAll(response.Body) + response.Body.Close() + return body } -- cgit v1.2.3