Implement multi-tenancy by adding a tenant_id column to your tables and filtering all queries with WHERE tenant_id = ? using a context value.
func GetUsers(ctx context.Context, db *sql.DB) ([]User, error) {
tenantID := ctx.Value("tenant_id").(string)
rows, err := db.QueryContext(ctx, "SELECT * FROM users WHERE tenant_id = ?", tenantID)
if err != nil { return nil, err }
defer rows.Close()
var users []User
for rows.Next() {
var u User
if err := rows.Scan(&u.ID, &u.Name, &u.TenantID); err != nil { return nil, err }
users = append(users, u)
}
return users, nil
}
- Add a
tenant_idcolumn to your database schema for every table that holds tenant data. - Store the tenant identifier in the request context at the entry point of your application.
- Pass the context to your database queries and enforce the
tenant_idfilter in every SQL statement. - Use a middleware or wrapper function to automatically inject the tenant ID into the context for every incoming request.