esbot/internal/http/http.go

52 lines
1.2 KiB
Go

package http
import (
"crypto/tls"
"encoding/json"
"net/http"
"git.netflux.io/rob/esbot/internal/matrix"
"github.com/rs/zerolog"
)
type handler struct {
logger zerolog.Logger
ep matrix.EventProcessor
}
func (h *handler) handleTransactions(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var payload EventsRequest
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
if err := h.ep.ProcessEvents(payload.RawEvents); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
}
func ListenAndServe(listenAddr, baseURL, user, accessToken string, insecureTLS bool, logger zerolog.Logger) error {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: insecureTLS}
h := handler{
logger: logger,
ep: matrix.NewProcessor(baseURL, user, accessToken, logger),
}
mux := http.NewServeMux()
mux.HandleFunc("/transactions/", h.handleTransactions)
logger.Info().Msgf("Listening on %s...", listenAddr)
return http.ListenAndServe(listenAddr, loggerMiddleware(logger, mux))
}