-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (78 loc) · 2.13 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"os"
"strconv"
"github.com/eddie023/tenantx/pkg/store"
)
type Handler struct {
db *store.DB
}
func main() {
ctx := context.Background()
if err := run(ctx); err != nil {
slog.Error("startup", "error", err)
os.Exit(1)
}
}
func run(ctx context.Context) error {
ctx = store.SetTenantID(ctx, 0)
dbConnectionURI := os.Getenv("DB_CONNECTION_URI")
if dbConnectionURI == "" {
return fmt.Errorf("DB_CONNECTION_URI environment variable must be set")
}
db, err := store.NewDB(ctx, dbConnectionURI)
if err != nil {
return fmt.Errorf("failed db connection: %w", err)
}
h := Handler{
db: db,
}
mux := http.NewServeMux()
mux.HandleFunc("/alive", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
mux.HandleFunc("/products", h.getProducts)
slog.Info("server listening on", "port", "8848")
if err := http.ListenAndServe(":8848", mux); err != nil {
return fmt.Errorf("server failed: %w", err)
}
return nil
}
func (h *Handler) getProducts(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// NOTE: in Production you will get the tenantID ideally from authentication middleware
// for the demonstration purpose, I am getting it from query param.
tenantId := r.URL.Query().Get("tenantId")
if tenantId == "" {
ctx = store.SetTenantID(ctx, 0)
} else {
id, err := strconv.Atoi(tenantId)
if err != nil {
slog.Error("parsing tenantId", "invalid integer", tenantId, "err", err)
http.Error(w, "invalid tenantId: tenantId must be a valid integer", http.StatusBadGateway)
return
}
ctx = store.SetTenantID(ctx, id)
}
products, err := h.db.GetProducts(ctx)
if err != nil {
slog.Error("getting products failed", "err", err)
http.Error(w, "db failed", http.StatusInternalServerError)
return
}
out, err := json.Marshal(products)
if err != nil {
http.Error(w, "unable to marshal", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(out)
}