package pretix import ( "context" "encoding/json" "io" "log" "net/http" "sync" "git.luj0ga.de/franconian/matrix-pretix/internal/config" "git.luj0ga.de/franconian/matrix-pretix/internal/matrix" ) type Server struct { client http.Client matrix *matrix.Client } func NewServer(matrix *matrix.Client) *Server { return &Server{ matrix: matrix, } } func (s Server) ListenAndServe(config *config.ServerConfig, ctx context.Context, wg *sync.WaitGroup) error { http.HandleFunc("/", http.NotFound) http.HandleFunc("/order_placed", s.orderPlaced) server := http.Server{ Addr: config.ListenAddress, } go func() { wg.Add(1) defer wg.Done() <-ctx.Done() err := server.Shutdown(context.Background()) if err != nil { log.Print(err) } }() err := server.ListenAndServe() if err != http.ErrServerClosed { return err } return nil } func (s Server) orderPlaced(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Content-Type") != "application/json" { writeStatus(w, http.StatusBadRequest) return } decoder := json.NewDecoder(r.Body) var data map[string]interface{} err := decoder.Decode(&data) if err != nil { writeStatus(w, http.StatusBadRequest) return } log.Print(data) } func writeStatus(w http.ResponseWriter, code int) { w.WriteHeader(code) io.WriteString(w, http.StatusText(code)) }