/
main.go
341 lines (305 loc) 路 8.97 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
multitenancy "github.com/bartventer/gorm-multitenancy"
"github.com/bartventer/gorm-multitenancy/drivers/postgres"
nethttpmw "github.com/bartventer/gorm-multitenancy/middleware/nethttp"
"github.com/bartventer/gorm-multitenancy/scopes"
"github.com/go-chi/chi/v5"
middleware "github.com/go-chi/chi/v5/middleware"
"gorm.io/gorm"
)
var (
db *gorm.DB
)
const (
// TableNameTenant is the table name for the tenant model
TableNameTenant = "tenants"
// TableNameBook is the table name for the book model
TableNameBook = "books"
)
// TableName overrides the table name used by Tenant to `tenants`
func (u *Tenant) TableName() string { return TableNameTenant }
// Tenant is the tenant model
type Tenant struct {
gorm.Model
postgres.TenantModel
}
// Book is the book model
type Book struct {
ID uint `gorm:"primarykey" json:"id"`
Name string `json:"name"`
}
var _ multitenancy.TenantTabler = (*Book)(nil)
// TableName overrides the table name used by Book to `books`
func (u *Book) TableName() string { return TableNameBook }
// IsTenantTable returns true
func (u *Book) IsTenantTable() bool { return true }
type (
// CreateTenantBody is the request body for creating a tenant
CreateTenantBody struct {
DomainURL string `json:"domainUrl"`
}
// UpdateBookBody is the request body for updating a book
UpdateBookBody struct {
Name string `json:"name"`
}
// BookResponse is the response body for a book
BookResponse struct {
ID uint `json:"id"`
Name string `json:"name"`
}
// TenantResponse is the response body for a tenant
TenantResponse struct {
ID uint `json:"id"`
DomainURL string `json:"domainUrl"`
}
)
// create database connection, models, and tables
func init() {
var err error
db, err = gorm.Open(postgres.Open(fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable",
os.Getenv("DB_HOST"),
os.Getenv("DB_PORT"),
os.Getenv("DB_USER"),
os.Getenv("DB_NAME"),
os.Getenv("DB_PASSWORD"),
)), &gorm.Config{
PrepareStmt: true,
})
if err != nil {
panic(err)
}
// register models
postgres.RegisterModels(db, &Tenant{}, &Book{})
// create models
// create public schema
if err := postgres.MigratePublicSchema(db); err != nil {
panic(err)
}
// create tenants
tenants := []Tenant{
{
TenantModel: postgres.TenantModel{
DomainURL: "tenant1.example.com",
SchemaName: "tenant1",
},
},
{
TenantModel: postgres.TenantModel{
DomainURL: "tenant2.example.com",
SchemaName: "tenant2",
},
},
}
for _, tenant := range tenants {
if err := db.Where("domain_url = ?", tenant.DomainURL).FirstOrCreate(&tenant).Error; err != nil {
panic(err)
}
}
// create schemas for tenants, and migrate "private" tables
for _, tenant := range tenants {
postgres.CreateSchemaForTenant(db, tenant.SchemaName)
}
// Create data for tenant1 (private schema)
books := []Book{{Name: "Book 1"}, {Name: "Book 2"}}
db.Transaction(func(tx *gorm.DB) error {
// set search path to tenant
tx.Exec(fmt.Sprintf("SET search_path TO %s", tenants[0].SchemaName))
for _, book := range books {
if err := tx.Where("name = ?", book.Name).FirstOrCreate(&book).Error; err != nil {
return err
}
}
// Reset search path
tx.Exec(fmt.Sprintf("SET search_path TO %s", "public"))
return nil
})
}
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// create tenant middleware
mw := nethttpmw.WithTenant(nethttpmw.WithTenantConfig{
DB: db,
Skipper: func(r *http.Request) bool {
return strings.HasPrefix(r.URL.Path, "/tenants") // skip tenant routes
},
TenantGetters: nethttpmw.DefaultTenantGetters,
})
r.Use(mw)
// routes
r.Post("/tenants", createTenantHandler)
r.Get("/tenants/{id}", getTenantHandler)
r.Delete("/tenants/{id}", deleteTenantHandler)
r.Post("/books", createBookHandler)
r.Get("/books", getBooksHandler)
r.Delete("/books/{id}", deleteBookHandler)
r.Put("/books/{id}", updateBookHandler)
// start chi server
http.ListenAndServe(":8080", r)
}
func createTenantHandler(w http.ResponseWriter, r *http.Request) {
var body CreateTenantBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
tenant := &Tenant{
TenantModel: postgres.TenantModel{
DomainURL: body.DomainURL,
SchemaName: strings.Split(body.DomainURL, ".")[0],
},
}
// create tenant
if err := db.Create(tenant).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// create schema for tenant, and migrate "private" tables
if err := postgres.CreateSchemaForTenant(db, tenant.SchemaName); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
res := &TenantResponse{
ID: tenant.ID,
DomainURL: tenant.DomainURL,
}
if err := json.NewEncoder(w).Encode(res); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func getTenantHandler(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
tenant := &TenantResponse{}
if err := db.Table(TableNameTenant).First(tenant, id).Error; err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if err := json.NewEncoder(w).Encode(tenant); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func deleteTenantHandler(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
// get tenant
tenant := &Tenant{}
if err := db.First(tenant, id).Error; err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// delete schema for tenant
if err := postgres.DropSchemaForTenant(db, tenant.SchemaName); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// delete tenant
if err := db.Delete(&Tenant{}, id).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
func getBooksHandler(w http.ResponseWriter, r *http.Request) {
tenant, err := nethttpmw.TenantFromContext(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var books []BookResponse
if err := db.Table(TableNameBook).Scopes(scopes.WithTenantSchema(tenant)).Find(&books).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(books); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func createBookHandler(w http.ResponseWriter, r *http.Request) {
tenant, err := nethttpmw.TenantFromContext(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var book Book
if err := json.NewDecoder(r.Body).Decode(&book); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := db.Scopes(scopes.WithTenantSchema(tenant)).Create(&book).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(book); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
res := &BookResponse{
ID: book.ID,
Name: book.Name,
}
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(res); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func deleteBookHandler(w http.ResponseWriter, r *http.Request) {
tenant, err := nethttpmw.TenantFromContext(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
// get book
var book Book
if err := db.Scopes(scopes.WithTenantSchema(tenant)).First(&book, id).Error; err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// delete book
if err := db.Scopes(scopes.WithTenantSchema(tenant)).Delete(&Book{}, id).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
func updateBookHandler(w http.ResponseWriter, r *http.Request) {
tenant, err := nethttpmw.TenantFromContext(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
id, _ := strconv.Atoi(chi.URLParam(r, "id"))
var body UpdateBookBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// get book
var book Book
if err := db.Scopes(scopes.WithTenantSchema(tenant)).First(&book, id).Error; err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// update book
if err := db.Scopes(scopes.WithTenantSchema(tenant)).Model(&book).Updates(body).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(book); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}