middleware.go (2652B)
1 // Copyright 2026 Shivakumar (Certichain) 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package api 16 17 import ( 18 "log" 19 "net/http" 20 "runtime/debug" 21 "slices" 22 "time" 23 24 "golang.org/x/time/rate" 25 26 "certichain/api/respond" 27 ) 28 29 type Middleware func(http.Handler) http.Handler 30 31 // Recover handles panic recovery. 32 // Any panic inside a handler is caught, logged and converted into 33 // a 500 response instead of crashing the connection. 34 func Recover(next http.Handler) http.Handler { 35 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 36 defer func() { 37 if err := recover(); err != nil { 38 log.Printf("panic recovered: %v\n%s", err, debug.Stack()) 39 respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error") 40 } 41 }() 42 next.ServeHTTP(w, r) 43 }) 44 } 45 46 // statusRecorder exposes http.ResponseWriter with status code. 47 type statusRecorder struct { 48 http.ResponseWriter 49 status int 50 } 51 52 func (r *statusRecorder) WriteHeader(status int) { 53 r.status = status 54 r.ResponseWriter.WriteHeader(status) 55 } 56 57 // Logger wraps next, logging method, path, status, and latency for every request. 58 func Logger(next http.Handler) http.Handler { 59 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 60 start := time.Now() 61 rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} 62 63 next.ServeHTTP(rec.ResponseWriter, r) 64 65 log.Printf("%s %s %d %s", r.Method, r.URL.Path, rec.status, time.Since(start)) 66 }) 67 } 68 69 // RateLimit wraps next with a global token-bucket ratelimiter. 70 func RateLimit(rps float64, burst int) Middleware { 71 limiter := rate.NewLimiter(rate.Limit(rps), burst) 72 73 return func(next http.Handler) http.Handler { 74 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 75 if !limiter.Allow() { 76 respond.Error(w, http.StatusTooManyRequests, "rate_limited", "too many requests, slow down") 77 return 78 } 79 next.ServeHTTP(w, r) 80 }) 81 } 82 } 83 84 // Chain applies middleware to all the handlers in order. 85 func Chain(h http.Handler, middlewares ...Middleware) http.Handler { 86 for _, middleware := range slices.Backward(middlewares) { 87 h = middleware(h) 88 } 89 return h 90 }