Skip to content

Commit

Permalink
allow to use http middlewares
Browse files Browse the repository at this point in the history
Signed-off-by: Vasiliy Tolstov <[email protected]>
  • Loading branch information
vtolstov committed Feb 7, 2021
1 parent 1e4d56d commit dc1e05b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
12 changes: 11 additions & 1 deletion http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
13 changes: 12 additions & 1 deletion options.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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)
}

0 comments on commit dc1e05b

Please sign in to comment.