commit c223e4562ceff250e8042aeb57adb7f7aff4ba37
parent 21a54daf045c25b16dc838963f52e7f420b0eb13
Author: Shivakumar <[email protected]>
Date: Mon, 10 Aug 2026 21:26:34 +0530
feat(api): add middleware layer
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
2 files changed, 97 insertions(+), 1 deletion(-)
diff --git a/api/middleware.go b/api/middleware.go
@@ -0,0 +1,90 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package api
+
+import (
+ "log"
+ "net/http"
+ "runtime/debug"
+ "slices"
+ "time"
+
+ "golang.org/x/time/rate"
+
+ "certichain/api/respond"
+)
+
+type Middleware func(http.Handler) http.Handler
+
+// Recover handles panic recovery.
+// Any panic inside a handler is caught, logged and converted into
+// a 500 response instead of crashing the connection.
+func Recover(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ defer func() {
+ if err := recover(); err != nil {
+ log.Printf("panic recovered: %v\n%s", err, debug.Stack())
+ respond.Error(w, http.StatusInternalServerError, "server_error", "internal server error")
+ }
+ }()
+ next.ServeHTTP(w, r)
+ })
+}
+
+// statusRecorder exposes http.ResponseWriter with status code.
+type statusRecorder struct {
+ http.ResponseWriter
+ status int
+}
+
+func (r *statusRecorder) WriteHeader(status int) {
+ r.status = status
+ r.ResponseWriter.WriteHeader(status)
+}
+
+// Logger wraps next, logging method, path, status, and latency for every request.
+func Logger(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Now()
+ rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
+
+ next.ServeHTTP(rec.ResponseWriter, r)
+
+ log.Printf("%s %s %d %s", r.Method, r.URL.Path, rec.status, time.Since(start))
+ })
+}
+
+// RateLimit wraps next with a global token-bucket ratelimiter.
+func RateLimit(rps float64, burst int) Middleware {
+ limiter := rate.NewLimiter(rate.Limit(rps), burst)
+
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !limiter.Allow() {
+ respond.Error(w, http.StatusTooManyRequests, "rate_limited", "too many requests, slow down")
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+ }
+}
+
+// Chain applies middleware to all the handlers in order.
+func Chain(h http.Handler, middlewares ...Middleware) http.Handler {
+ for _, middleware := range slices.Backward(middlewares) {
+ h = middleware(h)
+ }
+ return h
+}
diff --git a/api/server.go b/api/server.go
@@ -34,9 +34,15 @@ type Deps struct {
func NewServer(addr string, deps Deps) *http.Server {
mux := NewRouter(deps)
+ handler := Chain(mux,
+ Recover,
+ Logger,
+ RateLimit(50, 100),
+ )
+
return &http.Server{
Addr: addr,
- Handler: mux,
+ Handler: handler,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,