matrix-pretix/internal/pretix/server.go

108 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-07-24 02:40:44 +02:00
package pretix
import (
"context"
2022-07-24 21:41:01 +02:00
"database/sql"
"fmt"
2022-07-24 02:40:44 +02:00
"io"
"log"
"net/http"
2022-07-24 21:41:01 +02:00
"strings"
2022-07-24 02:40:44 +02:00
"sync"
"git.luj0ga.de/franconian/matrix-pretix/internal/config"
"git.luj0ga.de/franconian/matrix-pretix/internal/matrix"
)
type Server struct {
client http.Client
2022-07-24 21:41:01 +02:00
config *config.ServerConfig
db *sql.DB
2022-07-24 02:40:44 +02:00
matrix *matrix.Client
}
2022-07-24 21:41:01 +02:00
func NewServer(config *config.ServerConfig, db *sql.DB, matrix *matrix.Client) *Server {
2022-07-24 02:40:44 +02:00
return &Server{
2022-07-24 21:41:01 +02:00
config: config,
db: db,
2022-07-24 02:40:44 +02:00
matrix: matrix,
}
}
2022-07-24 21:41:01 +02:00
func (s Server) ListenAndServe(ctx context.Context, wg *sync.WaitGroup) error {
err := s.createTables()
if err != nil {
return err
}
2022-07-24 02:40:44 +02:00
http.HandleFunc("/", http.NotFound)
http.HandleFunc("/order_placed", s.orderPlaced)
server := http.Server{
2022-07-24 21:41:01 +02:00
Addr: s.config.ListenAddress,
2022-07-24 02:40:44 +02:00
}
go func() {
wg.Add(1)
defer wg.Done()
<-ctx.Done()
err := server.Shutdown(context.Background())
if err != nil {
log.Print(err)
}
}()
2022-07-24 21:41:01 +02:00
log.Print("listening on ", s.config.ListenAddress)
2022-07-24 04:43:24 +02:00
2022-07-24 21:41:01 +02:00
err = server.ListenAndServe()
2022-07-24 02:40:44 +02:00
if err != http.ErrServerClosed {
return err
}
return nil
}
2022-07-24 21:41:01 +02:00
func (s Server) createTables() error {
tables := []string{
`CREATE TABLE IF NOT EXISTS orders (
code TEXT PRIMARY KEY ON CONFLICT IGNORE
);
`,
}
tx, err := s.db.Begin()
if err != nil {
return err
2022-07-24 02:40:44 +02:00
}
2022-07-24 21:41:01 +02:00
for _, table := range tables {
_, err := tx.Exec(table)
if err != nil {
if err := tx.Rollback(); err != nil {
log.Print(err)
}
return err
}
}
2022-07-24 02:40:44 +02:00
2022-07-24 21:41:01 +02:00
err = tx.Commit()
2022-07-24 02:40:44 +02:00
if err != nil {
2022-07-24 21:41:01 +02:00
return err
2022-07-24 02:40:44 +02:00
}
2022-07-24 21:41:01 +02:00
return nil
}
func (s Server) buildURL(endpoint string, args ...any) string {
baseURL := strings.TrimSuffix(s.config.BaseURL, "/")
return fmt.Sprintf(endpoint, append([]any{baseURL}, args...)...)
2022-07-24 02:40:44 +02:00
}
func writeStatus(w http.ResponseWriter, code int) {
w.WriteHeader(code)
io.WriteString(w, http.StatusText(code))
}