-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGo_Golang_Microservices_Reference.go
More file actions
4826 lines (4035 loc) · 126 KB
/
Go_Golang_Microservices_Reference.go
File metadata and controls
4826 lines (4035 loc) · 126 KB
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// GO (GOLANG) HIGH-PERFORMANCE APIs & MICROSERVICES - Comprehensive Reference - by Richard Rembert
// Go excels at building high-performance, concurrent APIs and microservices with excellent
// performance characteristics, built-in concurrency, and minimal resource footprint
// ═══════════════════════════════════════════════════════════════════════════════
// 1. SETUP AND ENVIRONMENT
// ═══════════════════════════════════════════════════════════════════════════════
/*
GO DEVELOPMENT SETUP:
1. Install Go:
# Download from https://golang.org/dl/
# Or using package managers:
# macOS (Homebrew)
brew install go
# Ubuntu/Debian
sudo apt update
sudo apt install golang-go
# Verify installation
go version
2. Environment Setup:
# Add to ~/.bashrc or ~/.zshrc
export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH
# For Go 1.11+ with modules (recommended)
export GO111MODULE=on
3. Initialize New Project:
mkdir my-microservice
cd my-microservice
go mod init github.com/username/my-microservice
4. Essential Dependencies (go.mod):
module github.com/username/my-microservice
go 1.21
require (
// Web Framework
github.com/gin-gonic/gin v1.9.1
github.com/gorilla/mux v1.8.0
github.com/labstack/echo/v4 v4.11.1
// Database
github.com/lib/pq v1.10.9
gorm.io/gorm v1.25.4
gorm.io/driver/postgres v1.5.2
github.com/go-redis/redis/v8 v8.11.5
// Microservices
google.golang.org/grpc v1.57.0
google.golang.org/protobuf v1.31.0
github.com/nats-io/nats.go v1.28.0
// Monitoring & Logging
github.com/prometheus/client_golang v1.16.0
github.com/sirupsen/logrus v1.9.3
go.uber.org/zap v1.25.0
// Configuration
github.com/spf13/viper v1.16.0
// Authentication & Security
github.com/golang-jwt/jwt/v5 v5.0.0
golang.org/x/crypto v0.12.0
// Testing
github.com/stretchr/testify v1.8.4
github.com/testcontainers/testcontainers-go v0.22.0
// Utilities
github.com/google/uuid v1.3.0
github.com/shopspring/decimal v1.3.1
)
5. Project Structure:
my-microservice/
├── cmd/
│ ├── api/
│ │ └── main.go
│ └── worker/
│ └── main.go
├── internal/
│ ├── config/
│ ├── handlers/
│ ├── middleware/
│ ├── models/
│ ├── repository/
│ ├── service/
│ └── utils/
├── pkg/
│ ├── logger/
│ ├── database/
│ └── auth/
├── api/
│ └── proto/
├── deployments/
│ ├── docker/
│ └── k8s/
├── scripts/
├── tests/
├── docs/
├── go.mod
├── go.sum
├── Dockerfile
└── README.md
6. Build and Run:
# Development
go run cmd/api/main.go
# Build binary
go build -o bin/api cmd/api/main.go
# Cross-compile
GOOS=linux GOARCH=amd64 go build -o bin/api-linux cmd/api/main.go
# Install dependencies
go mod tidy
go mod vendor
*/
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)
// ═══════════════════════════════════════════════════════════════════════════════
// 2. CONFIGURATION MANAGEMENT
// ═══════════════════════════════════════════════════════════════════════════════
// Config holds all configuration for the application
type Config struct {
Server ServerConfig `mapstructure:"server"`
Database DatabaseConfig `mapstructure:"database"`
Redis RedisConfig `mapstructure:"redis"`
JWT JWTConfig `mapstructure:"jwt"`
Logging LoggingConfig `mapstructure:"logging"`
Metrics MetricsConfig `mapstructure:"metrics"`
}
type ServerConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
ReadTimeout time.Duration `mapstructure:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
GracefulStop time.Duration `mapstructure:"graceful_stop"`
}
type DatabaseConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Name string `mapstructure:"name"`
SSLMode string `mapstructure:"ssl_mode"`
MaxOpenConns int `mapstructure:"max_open_conns"`
MaxIdleConns int `mapstructure:"max_idle_conns"`
MaxLifetime time.Duration `mapstructure:"max_lifetime"`
}
type RedisConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
PoolSize int `mapstructure:"pool_size"`
}
type JWTConfig struct {
SecretKey string `mapstructure:"secret_key"`
ExpirationTime time.Duration `mapstructure:"expiration_time"`
Issuer string `mapstructure:"issuer"`
}
type LoggingConfig struct {
Level string `mapstructure:"level"`
Format string `mapstructure:"format"`
Output string `mapstructure:"output"`
}
type MetricsConfig struct {
Enabled bool `mapstructure:"enabled"`
Path string `mapstructure:"path"`
Port int `mapstructure:"port"`
}
// LoadConfig loads configuration from files and environment variables
func LoadConfig() (*Config, error) {
// Set default values
viper.SetDefault("server.host", "0.0.0.0")
viper.SetDefault("server.port", 8080)
viper.SetDefault("server.read_timeout", "10s")
viper.SetDefault("server.write_timeout", "10s")
viper.SetDefault("server.idle_timeout", "60s")
viper.SetDefault("server.graceful_stop", "30s")
viper.SetDefault("database.host", "localhost")
viper.SetDefault("database.port", 5432)
viper.SetDefault("database.ssl_mode", "disable")
viper.SetDefault("database.max_open_conns", 25)
viper.SetDefault("database.max_idle_conns", 25)
viper.SetDefault("database.max_lifetime", "5m")
viper.SetDefault("redis.host", "localhost")
viper.SetDefault("redis.port", 6379)
viper.SetDefault("redis.db", 0)
viper.SetDefault("redis.pool_size", 10)
viper.SetDefault("jwt.expiration_time", "24h")
viper.SetDefault("jwt.issuer", "my-microservice")
viper.SetDefault("logging.level", "info")
viper.SetDefault("logging.format", "json")
viper.SetDefault("logging.output", "stdout")
viper.SetDefault("metrics.enabled", true)
viper.SetDefault("metrics.path", "/metrics")
viper.SetDefault("metrics.port", 9090)
// Environment variable binding
viper.AutomaticEnv()
viper.SetEnvPrefix("APP")
// Configuration file
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath("./configs")
viper.AddConfigPath("/etc/myservice")
// Read config file (optional)
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return nil, err
}
}
var config Config
if err := viper.Unmarshal(&config); err != nil {
return nil, err
}
return &config, nil
}
// ═══════════════════════════════════════════════════════════════════════════════
// 3. LOGGING AND MONITORING
// ═══════════════════════════════════════════════════════════════════════════════
package logger
import (
"context"
"os"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Logger wraps zap logger with additional functionality
type Logger struct {
*zap.Logger
sugar *zap.SugaredLogger
}
// NewLogger creates a new logger instance
func NewLogger(level, format, output string) (*Logger, error) {
var config zap.Config
switch format {
case "json":
config = zap.NewProductionConfig()
default:
config = zap.NewDevelopmentConfig()
}
// Set log level
switch level {
case "debug":
config.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
case "info":
config.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
case "warn":
config.Level = zap.NewAtomicLevelAt(zap.WarnLevel)
case "error":
config.Level = zap.NewAtomicLevelAt(zap.ErrorLevel)
default:
config.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
}
// Set output
if output != "stdout" {
config.OutputPaths = []string{output}
}
// Add caller information
config.EncoderConfig.CallerKey = "caller"
config.DisableCaller = false
// Add timestamp
config.EncoderConfig.TimeKey = "timestamp"
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
zapLogger, err := config.Build()
if err != nil {
return nil, err
}
return &Logger{
Logger: zapLogger,
sugar: zapLogger.Sugar(),
}, nil
}
// WithContext adds context fields to logger
func (l *Logger) WithContext(ctx context.Context) *Logger {
fields := extractFieldsFromContext(ctx)
newLogger := l.Logger.With(fields...)
return &Logger{
Logger: newLogger,
sugar: newLogger.Sugar(),
}
}
// WithFields adds custom fields to logger
func (l *Logger) WithFields(fields map[string]interface{}) *Logger {
zapFields := make([]zap.Field, 0, len(fields))
for k, v := range fields {
zapFields = append(zapFields, zap.Any(k, v))
}
newLogger := l.Logger.With(zapFields...)
return &Logger{
Logger: newLogger,
sugar: newLogger.Sugar(),
}
}
// Structured logging methods
func (l *Logger) InfoCtx(ctx context.Context, msg string, fields ...zap.Field) {
l.WithContext(ctx).Info(msg, fields...)
}
func (l *Logger) ErrorCtx(ctx context.Context, msg string, fields ...zap.Field) {
l.WithContext(ctx).Error(msg, fields...)
}
func (l *Logger) WarnCtx(ctx context.Context, msg string, fields ...zap.Field) {
l.WithContext(ctx).Warn(msg, fields...)
}
func (l *Logger) DebugCtx(ctx context.Context, msg string, fields ...zap.Field) {
l.WithContext(ctx).Debug(msg, fields...)
}
// Sugar methods for easier usage
func (l *Logger) Infof(template string, args ...interface{}) {
l.sugar.Infof(template, args...)
}
func (l *Logger) Errorf(template string, args ...interface{}) {
l.sugar.Errorf(template, args...)
}
func (l *Logger) Warnf(template string, args ...interface{}) {
l.sugar.Warnf(template, args...)
}
func (l *Logger) Debugf(template string, args ...interface{}) {
l.sugar.Debugf(template, args...)
}
// extractFieldsFromContext extracts logging fields from context
func extractFieldsFromContext(ctx context.Context) []zap.Field {
var fields []zap.Field
if requestID := ctx.Value("request_id"); requestID != nil {
fields = append(fields, zap.String("request_id", requestID.(string)))
}
if userID := ctx.Value("user_id"); userID != nil {
fields = append(fields, zap.String("user_id", userID.(string)))
}
if traceID := ctx.Value("trace_id"); traceID != nil {
fields = append(fields, zap.String("trace_id", traceID.(string)))
}
return fields
}
// Metrics package for Prometheus integration
package metrics
import (
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
// HTTP metrics
HTTPRequestsTotal = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"method", "endpoint", "status_code"},
)
HTTPRequestDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "HTTP request duration in seconds",
Buckets: prometheus.DefBuckets,
},
[]string{"method", "endpoint"},
)
// Database metrics
DatabaseConnectionsActive = promauto.NewGauge(
prometheus.GaugeOpts{
Name: "database_connections_active",
Help: "Number of active database connections",
},
)
DatabaseQueryDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Name: "database_query_duration_seconds",
Help: "Database query duration in seconds",
Buckets: []float64{.001, .005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10},
},
[]string{"operation", "table"},
)
// Application metrics
ActiveUsers = promauto.NewGauge(
prometheus.GaugeOpts{
Name: "active_users_total",
Help: "Number of currently active users",
},
)
BusinessOperationsTotal = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "business_operations_total",
Help: "Total number of business operations",
},
[]string{"operation", "status"},
)
)
// RecordHTTPRequest records HTTP request metrics
func RecordHTTPRequest(method, endpoint, statusCode string, duration time.Duration) {
HTTPRequestsTotal.WithLabelValues(method, endpoint, statusCode).Inc()
HTTPRequestDuration.WithLabelValues(method, endpoint).Observe(duration.Seconds())
}
// RecordDatabaseQuery records database query metrics
func RecordDatabaseQuery(operation, table string, duration time.Duration) {
DatabaseQueryDuration.WithLabelValues(operation, table).Observe(duration.Seconds())
}
// ═══════════════════════════════════════════════════════════════════════════════
// 4. DATABASE LAYER AND MODELS
// ═══════════════════════════════════════════════════════════════════════════════
package database
import (
"context"
"database/sql"
"fmt"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormLogger "gorm.io/gorm/logger"
"github.com/go-redis/redis/v8"
_ "github.com/lib/pq"
)
// Database holds database connections
type Database struct {
DB *gorm.DB
Redis *redis.Client
}
// NewDatabase creates a new database instance
func NewDatabase(dbConfig DatabaseConfig, redisConfig RedisConfig) (*Database, error) {
// PostgreSQL connection
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
dbConfig.Host, dbConfig.Port, dbConfig.User, dbConfig.Password, dbConfig.Name, dbConfig.SSLMode)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: gormLogger.Default.LogMode(gormLogger.Info),
NowFunc: func() time.Time {
return time.Now().UTC()
},
})
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
// Configure connection pool
sqlDB, err := db.DB()
if err != nil {
return nil, fmt.Errorf("failed to get underlying sql.DB: %w", err)
}
sqlDB.SetMaxOpenConns(dbConfig.MaxOpenConns)
sqlDB.SetMaxIdleConns(dbConfig.MaxIdleConns)
sqlDB.SetConnMaxLifetime(dbConfig.MaxLifetime)
// Redis connection
rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port),
Password: redisConfig.Password,
DB: redisConfig.DB,
PoolSize: redisConfig.PoolSize,
})
// Test Redis connection
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := rdb.Ping(ctx).Err(); err != nil {
return nil, fmt.Errorf("failed to connect to Redis: %w", err)
}
return &Database{
DB: db,
Redis: rdb,
}, nil
}
// Close closes database connections
func (d *Database) Close() error {
sqlDB, err := d.DB.DB()
if err != nil {
return err
}
if err := sqlDB.Close(); err != nil {
return err
}
return d.Redis.Close()
}
// Health check
func (d *Database) Health(ctx context.Context) error {
// Check PostgreSQL
sqlDB, err := d.DB.DB()
if err != nil {
return err
}
if err := sqlDB.PingContext(ctx); err != nil {
return fmt.Errorf("postgres health check failed: %w", err)
}
// Check Redis
if err := d.Redis.Ping(ctx).Err(); err != nil {
return fmt.Errorf("redis health check failed: %w", err)
}
return nil
}
// Models
package models
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"golang.org/x/crypto/bcrypt"
)
// BaseModel contains common fields for all models
type BaseModel struct {
ID uuid.UUID `json:"id" gorm:"type:uuid;primary_key;default:gen_random_uuid()"`
CreatedAt time.Time `json:"created_at" gorm:"not null"`
UpdatedAt time.Time `json:"updated_at" gorm:"not null"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}
// User represents a user in the system
type User struct {
BaseModel
Email string `json:"email" gorm:"uniqueIndex;not null"`
Username string `json:"username" gorm:"uniqueIndex;not null"`
Password string `json:"-" gorm:"not null"`
FirstName string `json:"first_name" gorm:"not null"`
LastName string `json:"last_name" gorm:"not null"`
Role UserRole `json:"role" gorm:"not null;default:'user'"`
Status UserStatus `json:"status" gorm:"not null;default:'active'"`
LastLoginAt *time.Time `json:"last_login_at"`
// Relationships
Posts []Post `json:"posts,omitempty" gorm:"foreignKey:UserID"`
Comments []Comment `json:"comments,omitempty" gorm:"foreignKey:UserID"`
}
type UserRole string
const (
UserRoleUser UserRole = "user"
UserRoleModerator UserRole = "moderator"
UserRoleAdmin UserRole = "admin"
)
type UserStatus string
const (
UserStatusActive UserStatus = "active"
UserStatusInactive UserStatus = "inactive"
UserStatusSuspended UserStatus = "suspended"
)
// SetPassword hashes and sets the user password
func (u *User) SetPassword(password string) error {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
u.Password = string(hashedPassword)
return nil
}
// CheckPassword verifies the provided password
func (u *User) CheckPassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
return err == nil
}
// FullName returns the user's full name
func (u *User) FullName() string {
return u.FirstName + " " + u.LastName
}
// IsAdmin checks if user has admin role
func (u *User) IsAdmin() bool {
return u.Role == UserRoleAdmin
}
// CanModerate checks if user can moderate content
func (u *User) CanModerate() bool {
return u.Role == UserRoleAdmin || u.Role == UserRoleModerator
}
// Post represents a blog post or article
type Post struct {
BaseModel
Title string `json:"title" gorm:"not null"`
Slug string `json:"slug" gorm:"uniqueIndex;not null"`
Content string `json:"content" gorm:"type:text;not null"`
Excerpt string `json:"excerpt" gorm:"type:text"`
Status PostStatus `json:"status" gorm:"not null;default:'draft'"`
Featured bool `json:"featured" gorm:"default:false"`
ViewCount int64 `json:"view_count" gorm:"default:0"`
PublishedAt *time.Time `json:"published_at"`
// Foreign keys
UserID uuid.UUID `json:"user_id" gorm:"not null"`
CategoryID uuid.UUID `json:"category_id" gorm:"not null"`
// Relationships
User User `json:"user" gorm:"foreignKey:UserID"`
Category Category `json:"category" gorm:"foreignKey:CategoryID"`
Comments []Comment `json:"comments,omitempty" gorm:"foreignKey:PostID"`
Tags []Tag `json:"tags,omitempty" gorm:"many2many:post_tags;"`
}
type PostStatus string
const (
PostStatusDraft PostStatus = "draft"
PostStatusPublished PostStatus = "published"
PostStatusArchived PostStatus = "archived"
)
// IsPublished checks if post is published
func (p *Post) IsPublished() bool {
return p.Status == PostStatusPublished && p.PublishedAt != nil
}
// ReadingTime calculates estimated reading time in minutes
func (p *Post) ReadingTime() int {
words := len([]rune(p.Content)) / 5 // Rough estimate: 5 chars per word
minutes := words / 200 // 200 words per minute
if minutes < 1 {
return 1
}
return minutes
}
// Category represents a post category
type Category struct {
BaseModel
Name string `json:"name" gorm:"not null"`
Slug string `json:"slug" gorm:"uniqueIndex;not null"`
Description string `json:"description" gorm:"type:text"`
Color string `json:"color" gorm:"default:'#3B82F6'"`
PostCount int64 `json:"post_count" gorm:"default:0"`
// Relationships
Posts []Post `json:"posts,omitempty" gorm:"foreignKey:CategoryID"`
}
// Comment represents a comment on a post
type Comment struct {
BaseModel
Content string `json:"content" gorm:"type:text;not null"`
Status CommentStatus `json:"status" gorm:"not null;default:'pending'"`
// Foreign keys
PostID uuid.UUID `json:"post_id" gorm:"not null"`
UserID uuid.UUID `json:"user_id" gorm:"not null"`
ParentID *uuid.UUID `json:"parent_id"`
// Relationships
Post Post `json:"post" gorm:"foreignKey:PostID"`
User User `json:"user" gorm:"foreignKey:UserID"`
Parent *Comment `json:"parent,omitempty" gorm:"foreignKey:ParentID"`
Replies []Comment `json:"replies,omitempty" gorm:"foreignKey:ParentID"`
}
type CommentStatus string
const (
CommentStatusPending CommentStatus = "pending"
CommentStatusApproved CommentStatus = "approved"
CommentStatusRejected CommentStatus = "rejected"
)
// IsApproved checks if comment is approved
func (c *Comment) IsApproved() bool {
return c.Status == CommentStatusApproved
}
// Tag represents a content tag
type Tag struct {
BaseModel
Name string `json:"name" gorm:"uniqueIndex;not null"`
Slug string `json:"slug" gorm:"uniqueIndex;not null"`
PostCount int64 `json:"post_count" gorm:"default:0"`
// Relationships
Posts []Post `json:"posts,omitempty" gorm:"many2many:post_tags;"`
}
// Migration function
func MigrateModels(db *gorm.DB) error {
return db.AutoMigrate(
&User{},
&Category{},
&Post{},
&Comment{},
&Tag{},
)
}
// ═══════════════════════════════════════════════════════════════════════════════
// 5. REPOSITORY LAYER
// ═══════════════════════════════════════════════════════════════════════════════
package repository
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"github.com/go-redis/redis/v8"
"gorm.io/gorm"
)
// BaseRepository provides common repository functionality
type BaseRepository struct {
db *gorm.DB
redis *redis.Client
}
// NewBaseRepository creates a new base repository
func NewBaseRepository(db *gorm.DB, redis *redis.Client) *BaseRepository {
return &BaseRepository{
db: db,
redis: redis,
}
}
// CacheGet retrieves data from cache
func (r *BaseRepository) CacheGet(ctx context.Context, key string, dest interface{}) error {
val, err := r.redis.Get(ctx, key).Result()
if err != nil {
return err
}
return json.Unmarshal([]byte(val), dest)
}
// CacheSet stores data in cache
func (r *BaseRepository) CacheSet(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
data, err := json.Marshal(value)
if err != nil {
return err
}
return r.redis.Set(ctx, key, data, expiration).Err()
}
// CacheDelete removes data from cache
func (r *BaseRepository) CacheDelete(ctx context.Context, keys ...string) error {
if len(keys) == 0 {
return nil
}
return r.redis.Del(ctx, keys...).Err()
}
// UserRepository handles user data operations
type UserRepository struct {
*BaseRepository
}
// NewUserRepository creates a new user repository
func NewUserRepository(db *gorm.DB, redis *redis.Client) *UserRepository {
return &UserRepository{
BaseRepository: NewBaseRepository(db, redis),
}
}
// Create creates a new user
func (r *UserRepository) Create(ctx context.Context, user *User) error {
if err := r.db.WithContext(ctx).Create(user).Error; err != nil {
return fmt.Errorf("failed to create user: %w", err)
}
// Cache the user
cacheKey := fmt.Sprintf("user:%s", user.ID.String())
r.CacheSet(ctx, cacheKey, user, time.Hour)
return nil
}
// GetByID retrieves a user by ID
func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (*User, error) {
// Try cache first
cacheKey := fmt.Sprintf("user:%s", id.String())
var user User
if err := r.CacheGet(ctx, cacheKey, &user); err == nil {
return &user, nil
}
// Cache miss, get from database
if err := r.db.WithContext(ctx).First(&user, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, fmt.Errorf("user not found")
}
return nil, fmt.Errorf("failed to get user: %w", err)
}
// Cache the result
r.CacheSet(ctx, cacheKey, &user, time.Hour)
return &user, nil
}
// GetByEmail retrieves a user by email
func (r *UserRepository) GetByEmail(ctx context.Context, email string) (*User, error) {
var user User
if err := r.db.WithContext(ctx).Where("email = ?", email).First(&user).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, fmt.Errorf("user not found")
}
return nil, fmt.Errorf("failed to get user: %w", err)
}
return &user, nil
}
// Update updates a user
func (r *UserRepository) Update(ctx context.Context, user *User) error {
if err := r.db.WithContext(ctx).Save(user).Error; err != nil {
return fmt.Errorf("failed to update user: %w", err)
}
// Invalidate cache
cacheKey := fmt.Sprintf("user:%s", user.ID.String())
r.CacheDelete(ctx, cacheKey)
return nil
}
// Delete deletes a user
func (r *UserRepository) Delete(ctx context.Context, id uuid.UUID) error {
if err := r.db.WithContext(ctx).Delete(&User{}, id).Error; err != nil {
return fmt.Errorf("failed to delete user: %w", err)
}
// Invalidate cache
cacheKey := fmt.Sprintf("user:%s", id.String())
r.CacheDelete(ctx, cacheKey)
return nil
}
// List retrieves users with pagination
func (r *UserRepository) List(ctx context.Context, offset, limit int) ([]User, int64, error) {
var users []User
var total int64
// Get total count
if err := r.db.WithContext(ctx).Model(&User{}).Count(&total).Error; err != nil {
return nil, 0, fmt.Errorf("failed to count users: %w", err)
}
// Get users with pagination
if err := r.db.WithContext(ctx).
Offset(offset).
Limit(limit).
Order("created_at DESC").
Find(&users).Error; err != nil {
return nil, 0, fmt.Errorf("failed to list users: %w", err)
}
return users, total, nil
}
// PostRepository handles post data operations
type PostRepository struct {
*BaseRepository
}
// NewPostRepository creates a new post repository
func NewPostRepository(db *gorm.DB, redis *redis.Client) *PostRepository {
return &PostRepository{
BaseRepository: NewBaseRepository(db, redis),
}
}
// Create creates a new post
func (r *PostRepository) Create(ctx context.Context, post *Post) error {
if err := r.db.WithContext(ctx).Create(post).Error; err != nil {
return fmt.Errorf("failed to create post: %w", err)
}
// Invalidate related caches
r.CacheDelete(ctx, "posts:published", "posts:featured")
return nil
}
// GetByID retrieves a post by ID with relationships
func (r *PostRepository) GetByID(ctx context.Context, id uuid.UUID) (*Post, error) {
var post Post
if err := r.db.WithContext(ctx).
Preload("User").
Preload("Category").
Preload("Tags").
Preload("Comments", func(db *gorm.DB) *gorm.DB {
return db.Where("status = ?", CommentStatusApproved).Order("created_at DESC")
}).
Preload("Comments.User").
First(&post, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, fmt.Errorf("post not found")
}
return nil, fmt.Errorf("failed to get post: %w", err)
}
return &post, nil
}
// GetBySlug retrieves a post by slug
func (r *PostRepository) GetBySlug(ctx context.Context, slug string) (*Post, error) {
var post Post