希望这是获得一些代表的简单方法。这看起来很简单,所以我一定做错了什么,只是看不到它。
我有一个简单的中间件,它是一个事务ID,并将其添加到请求和响应头。
func HandleTransactionID(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
tid := uuid.NewV4()
req.Header.Set(TransIDHeader, TransIDPrefix + tid.String())
w.Header().Set(TransIDHeader, TransIDPrefix + tid.String())
fn(w, req)
}
}
在我的单元测试中,我已确认响应标头已成功设置,但未设置请求标头。我认为可以修改请求标头,所以?
const (
WriteTestHeader = "WriterTransHeader"
RequestTestHeader = "ReqTransHeader"
)
func recorderFunc(w http.ResponseWriter, req *http.Request){
w.Header().Set(WriteTestHeader, w.Header().Get(TransIDHeader))
w.Header().Set(RequestTestHeader, req.Header.Get(TransIDHeader))
}
func TestHandleTransactionID(t *testing.T) {
recorder := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/foo", nil)
middleware.HandleTransactionID(recorderFunc)(recorder, req)
if req.Header.Get(RequestTestHeader) == "" {
t.Error("request header is nil")
}
if recorder.Header().Get(WriteTestHeader) == "" {
t.Error("response header is nil")
}
if req.Header.Get(RequestTestHeader) != recorder.Header().Get(WriteTestHeader) {
t.Errorf("header value mismatch: %s != %s",
req.Header.Get(RequestTestHeader),
recorder.Header().Get(WriteTestHeader))
}
}
答案 0 :(得分:0)
在您的测试中,req.Header.Get(RequestTestHeader)
将始终为空字符串,因为您没有将密钥设置为' RequestTestHeader'在请求标头中,但在ResponseWriter w.Header().Set(RequestTestHeader, req.Header.Get(TransIDHeader))
在一个不相关的说明中,使用http.Handler接口func HandleTransactionID(fn http.Handler) http.Handler
来获取中间件函数签名将被认为是Goomatic。