From 1cb40831a4ef52e974fd5175c537ea04cbd30d91 Mon Sep 17 00:00:00 2001 From: Asim Aslam Date: Sun, 18 Nov 2018 20:40:43 +0000 Subject: [PATCH] add http handler option for broker --- broker/http/http.go | 2 ++ broker/http/options.go | 23 +++++++++++++++++++++++ broker/http_broker.go | 12 ++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 broker/http/options.go diff --git a/broker/http/http.go b/broker/http/http.go index d54d2f38..7d09986a 100644 --- a/broker/http/http.go +++ b/broker/http/http.go @@ -1,9 +1,11 @@ +// Package http provides a http based message broker package http import ( "github.com/micro/go-micro/broker" ) +// NewBroker returns a new http broker func NewBroker(opts ...broker.Option) broker.Broker { return broker.NewBroker(opts...) } diff --git a/broker/http/options.go b/broker/http/options.go new file mode 100644 index 00000000..03240c42 --- /dev/null +++ b/broker/http/options.go @@ -0,0 +1,23 @@ +package http + +import ( + "context" + "net/http" + + "github.com/micro/go-micro/broker" +) + +// Handle registers the handler for the given pattern. +func Handle(pattern string, handler http.Handler) broker.Option { + return func(o *broker.Options) { + if o.Context == nil { + o.Context = context.Background() + } + handlers, ok := o.Context.Value("http_handlers").(map[string]http.Handler) + if !ok { + handlers = make(map[string]http.Handler) + } + handlers[pattern] = handler + o.Context = context.WithValue(o.Context, "http_handlers", handlers) + } +} diff --git a/broker/http_broker.go b/broker/http_broker.go index a3e814fe..c43d85be 100644 --- a/broker/http_broker.go +++ b/broker/http_broker.go @@ -126,7 +126,19 @@ func newHttpBroker(opts ...Option) Broker { mux: http.NewServeMux(), } + // specify the message handler h.mux.Handle(DefaultSubPath, h) + + // get optional handlers + if h.opts.Context != nil { + handlers, ok := h.opts.Context.Value("http_handlers").(map[string]http.Handler) + if ok { + for pattern, handler := range handlers { + h.mux.Handle(pattern, handler) + } + } + } + return h }