From dc1e05bb18fc0443b42a78c1721cc2ab19de35a4 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Sun, 7 Feb 2021 13:27:28 +0300 Subject: [PATCH] allow to use http middlewares Signed-off-by: Vasiliy Tolstov --- http.go | 12 +++++++++++- options.go | 13 ++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/http.go b/http.go index 2579d89..61bf18b 100644 --- a/http.go +++ b/http.go @@ -375,7 +375,17 @@ func (h *httpServer) Start() error { } } - go http.Serve(ts, handler) + fn := handler + if h.opts.Context != nil { + if mwf, ok := h.opts.Context.Value(middlewareKey{}).([]func(http.Handler) http.Handler); ok && len(mwf) > 0 { + // wrap the handler func + for i := len(mwf); i > 0; i-- { + fn = mwf[i-1](fn) + } + } + } + + go http.Serve(ts, fn) go func() { t := new(time.Ticker) diff --git a/options.go b/options.go index 559e81d..e77dfde 100644 --- a/options.go +++ b/options.go @@ -1,6 +1,11 @@ package http -import "context" +import ( + "context" + "net/http" + + "github.com/unistack-org/micro/v3/server" +) type rspCodeKey struct{} type rspCodeVal struct { @@ -22,3 +27,9 @@ func GetRspCode(ctx context.Context) int { } return code } + +type middlewareKey struct{} + +func Middleware(mw ...func(http.Handler) http.Handler) server.Option { + return server.SetOption(middlewareKey{}, mw) +}