我的概念很简单,我想添加请求 ID(由 chi 生成middleware.RequestID
到响应头)。
我下面的代码添加X-Request-Id
但不添加 ID 本身。我不确定为什么,因为它在上下文中肯定是可用的,因为middleware.RequestID
在中间件链中更高?
我的路由器创建:
package rest
import (
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"goWebAPI/pkg/database"
"goWebAPI/pkg/rest/mw"
"goWebAPI/pkg/rest/routes"
)
func GetRouter(db *database.Database) *chi.Mux {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(mw.SendRequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(60 * time.Second))
r.Get("/", routes.IndexRoute())
return r
}
我的自定义中间件:
package mw
import (
"context"
"net/http"
"github.com/go-chi/chi/v5/middleware"
)
const requestIDHeader = "X-Request-Id"
func SendRequestID(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if w.Header().Get(requestIDHeader) == "" {
w.Header().Add(
requestIDHeader,
middleware.GetReqID(context.Background()),
)
}
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
我的索引路线:
package routes
import "net/http"
func IndexRoute() http.HandlerFunc {
fn:= func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("welcome"))
}
return fn
}