diff --git a/.env b/.env index b1baa65..f921b80 100644 --- a/.env +++ b/.env @@ -3,3 +3,5 @@ DATABASE_URL=postgres://postgres:password@localhost:5432/counter_db?sslmode=disa PORT=8080 LOG_LEVEL=info GIN_MODE=debug +METRICS_PORT=9090 +JWT_SECRET=your-super-secure-development-secret-key-here diff --git a/.env.production b/.env.production index 3512ca5..a6859d4 100644 --- a/.env.production +++ b/.env.production @@ -5,3 +5,4 @@ JWT_SECRET=super-secure-production-secret-change-this PORT=8080 GIN_MODE=release LOG_LEVEL=warn +METRICS_PORT=9090 diff --git a/auth.go b/auth.go index a4ab630..9d18238 100644 --- a/auth.go +++ b/auth.go @@ -122,6 +122,7 @@ func AuthMiddleware() gin.HandlerFunc { func RegisterHandler(c *gin.Context) { var req RegisterRequest if err := c.ShouldBindJSON(&req); err != nil { + RecordAuthAttempt("register", "bad_request") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } @@ -130,6 +131,7 @@ func RegisterHandler(c *gin.Context) { var existingUser User err := db.QueryRow("SELECT id FROM users WHERE username = $1 OR email = $2", req.Username, req.Email).Scan(&existingUser.ID) if err != sql.ErrNoRows { + RecordAuthAttempt("register", "conflict") c.JSON(http.StatusConflict, gin.H{"error": "Username or email already exists"}) return } @@ -160,6 +162,7 @@ func RegisterHandler(c *gin.Context) { return } + RecordAuthAttempt("register", "success") c.JSON(http.StatusCreated, AuthResponse{ Token: token, User: user, @@ -170,6 +173,7 @@ func RegisterHandler(c *gin.Context) { func LoginHandler(c *gin.Context) { var req LoginRequest if err := c.ShouldBindJSON(&req); err != nil { + RecordAuthAttempt("login", "bad_request") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } @@ -182,15 +186,18 @@ func LoginHandler(c *gin.Context) { ).Scan(&user.ID, &user.Username, &user.Email, &user.Password, &user.CreatedAt, &user.UpdatedAt) if err == sql.ErrNoRows { + RecordAuthAttempt("login", "user_not_found") c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials 1"}) return } else if err != nil { + RecordAuthAttempt("login", "database_error") c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error"}) return } // Check password if !checkPasswordHash(req.Password, user.Password) { + RecordAuthAttempt("login", "invalid_password") c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid credentials 2"}) return } @@ -205,6 +212,7 @@ func LoginHandler(c *gin.Context) { // Clear password from response user.Password = "" + RecordAuthAttempt("login", "success") c.JSON(http.StatusOK, AuthResponse{ Token: token, User: user, diff --git a/config.go b/config.go index 264591f..47c18f9 100644 --- a/config.go +++ b/config.go @@ -22,6 +22,7 @@ type Config struct { DatabaseURL string JWTSecret string Port string + MetricsPort string GinMode string LogLevel string Debug bool @@ -41,6 +42,7 @@ func LoadConfig() *Config { DatabaseURL: getEnv("DATABASE_URL", getDefaultDatabaseURL(env)), JWTSecret: getRequiredEnv("JWT_SECRET"), Port: getEnv("PORT", "8080"), + MetricsPort: getEnv("METRICS_PORT", "9090"), GinMode: getGinMode(env), LogLevel: getLogLevel(env), Debug: env == Development, @@ -180,6 +182,7 @@ func logConfig(config *Config) { log.Printf("║ 🔧 DEBUG: %-20s ║", fmt.Sprintf("%t", config.Debug)) log.Printf("║ 📊 LOG LEVEL: %-15s ║", config.LogLevel) log.Printf("║ 🌐 PORT: %-20s ║", config.Port) + log.Printf("║ 📈 METRICS PORT: %-15s ║", config.MetricsPort) log.Printf("║ ║") log.Printf("║ 📁 Configuration Files Loaded: ║") log.Printf("║ • .env (base configuration) ║") diff --git a/counters.go b/counters.go index 5fd6d67..c3afc46 100644 --- a/counters.go +++ b/counters.go @@ -27,10 +27,13 @@ func CreateCounterHandler(c *gin.Context) { ).Scan(&counter.ID, &counter.UserID, &counter.Name, &counter.Description, &counter.CreatedAt, &counter.UpdatedAt) if err != nil { + RecordDBOperation("insert", "counters") c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create counter"}) return } + RecordDBOperation("insert", "counters") + c.JSON(http.StatusCreated, counter) } @@ -61,11 +64,14 @@ func GetCountersHandler(c *gin.Context) { rows, err := db.Query(query, args...) if err != nil { + RecordDBOperation("select", "counters") c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch counters"}) return } defer rows.Close() + RecordDBOperation("select", "counters") + counters := []CounterWithStats{} // Initialize as empty slice, not nil for rows.Next() { var counter CounterWithStats diff --git a/go.mod b/go.mod index 217c581..eba4e97 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,8 @@ module counter -go 1.21 +go 1.23.0 + +toolchain go1.24.2 require ( github.com/gin-contrib/cors v1.7.0 @@ -8,12 +10,15 @@ require ( github.com/golang-jwt/jwt/v5 v5.2.1 github.com/joho/godotenv v1.5.1 github.com/lib/pq v1.10.9 - golang.org/x/crypto v0.23.0 + github.com/prometheus/client_golang v1.23.2 + golang.org/x/crypto v0.41.0 ) require ( + github.com/beorn7/perks v1.0.1 // indirect github.com/bytedance/sonic v1.11.6 // indirect github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/iasm v0.2.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect @@ -29,13 +34,18 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.66.1 // indirect + github.com/prometheus/procfs v0.16.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect + go.yaml.in/yaml/v2 v2.4.2 // indirect golang.org/x/arch v0.8.0 // indirect - golang.org/x/net v0.25.0 // indirect - golang.org/x/sys v0.20.0 // indirect - golang.org/x/text v0.15.0 // indirect - google.golang.org/protobuf v1.34.1 // indirect + golang.org/x/net v0.43.0 // indirect + golang.org/x/sys v0.35.0 // indirect + golang.org/x/text v0.28.0 // indirect + google.golang.org/protobuf v1.36.8 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 0d7f5af..070c7af 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,11 @@ +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= @@ -30,21 +34,25 @@ github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= @@ -56,12 +64,22 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= -github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= +github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= +github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= +github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -72,29 +90,32 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= +go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= -golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= -golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= -golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= -golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= +golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= +golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE= +golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= -golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= -golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= -google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng= +golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU= +google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc= +google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/main.go b/main.go index d92e0df..c6142f0 100644 --- a/main.go +++ b/main.go @@ -27,6 +27,12 @@ func main() { log.Fatal("Failed to create tables:", err) } + // Initialize Prometheus metrics + InitMetrics() + + // Start metrics server on separate port + StartMetricsServer(config.MetricsPort) + // Create Gin router r := gin.Default() @@ -38,6 +44,9 @@ func main() { corsConfig.AllowCredentials = true r.Use(cors.New(corsConfig)) + // Add metrics middleware + r.Use(MetricsMiddleware()) + // Health check endpoint r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ok"}) @@ -85,6 +94,7 @@ func main() { log.Printf(" 📊 Health check: http://localhost:%s/health", port) log.Printf(" 🔗 API endpoint: http://localhost:%s/api/v1", port) log.Printf(" 🎨 Frontend: http://localhost:%s/", port) + log.Printf(" 📈 Metrics: http://localhost:%s/metrics", config.MetricsPort) log.Printf("") log.Printf("✅ Server is ready and accepting connections!") log.Printf("") diff --git a/metrics.go b/metrics.go new file mode 100644 index 0000000..1f75b06 --- /dev/null +++ b/metrics.go @@ -0,0 +1,137 @@ +package main + +import ( + "log" + "net/http" + "strconv" + "time" + + "github.com/gin-gonic/gin" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +var ( + // HTTP request metrics + httpRequestsTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "http_requests_total", + Help: "Total number of HTTP requests", + }, + []string{"method", "endpoint", "status_code"}, + ) + + // HTTP request duration metrics + httpRequestDuration = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "http_request_duration_seconds", + Help: "HTTP request duration in seconds", + Buckets: prometheus.DefBuckets, + }, + []string{"method", "endpoint"}, + ) + + // API endpoint specific metrics + apiRequestsTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "api_requests_total", + Help: "Total number of API requests by endpoint", + }, + []string{"endpoint", "method"}, + ) + + // Database operation metrics + dbOperationsTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "db_operations_total", + Help: "Total number of database operations", + }, + []string{"operation", "table"}, + ) + + // Authentication metrics + authAttemptsTotal = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "auth_attempts_total", + Help: "Total number of authentication attempts", + }, + []string{"type", "status"}, + ) +) + +// InitMetrics initializes Prometheus metrics +func InitMetrics() { + // Register all metrics + prometheus.MustRegister(httpRequestsTotal) + prometheus.MustRegister(httpRequestDuration) + prometheus.MustRegister(apiRequestsTotal) + prometheus.MustRegister(dbOperationsTotal) + prometheus.MustRegister(authAttemptsTotal) +} + +// StartMetricsServer starts the metrics server on a separate port +func StartMetricsServer(port string) { + // Create a new HTTP server for metrics + metricsMux := http.NewServeMux() + metricsMux.Handle("/metrics", promhttp.Handler()) + + // Add health check for metrics server + metricsMux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + w.Write([]byte("Metrics server is healthy")) + }) + + server := &http.Server{ + Addr: "localhost:" + port, + Handler: metricsMux, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + } + + go func() { + log.Printf("📈 Metrics server starting on http://localhost:%s/metrics", port) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Printf("❌ Metrics server failed to start: %v", err) + } + }() +} + +// MetricsMiddleware is a Gin middleware to collect HTTP metrics +func MetricsMiddleware() gin.HandlerFunc { + return func(c *gin.Context) { + start := time.Now() + path := c.FullPath() + method := c.Request.Method + + // Process request + c.Next() + + // Calculate duration + duration := time.Since(start).Seconds() + statusCode := strconv.Itoa(c.Writer.Status()) + + // Record metrics + httpRequestsTotal.WithLabelValues(method, path, statusCode).Inc() + httpRequestDuration.WithLabelValues(method, path).Observe(duration) + + // Record API-specific metrics for API routes + if c.Request.URL.Path[:4] == "/api" { + apiRequestsTotal.WithLabelValues(path, method).Inc() + } + } +} + +// RecordAPICall records a specific API endpoint call +func RecordAPICall(endpoint, method string) { + apiRequestsTotal.WithLabelValues(endpoint, method).Inc() +} + +// RecordDBOperation records a database operation +func RecordDBOperation(operation, table string) { + dbOperationsTotal.WithLabelValues(operation, table).Inc() +} + +// RecordAuthAttempt records an authentication attempt +func RecordAuthAttempt(authType, status string) { + authAttemptsTotal.WithLabelValues(authType, status).Inc() +}