From 1d8047a272ef38ef42b6de4852e7629fe5ebfc83 Mon Sep 17 00:00:00 2001 From: Asim Aslam Date: Sun, 18 Nov 2018 16:32:53 +0000 Subject: [PATCH] add option to set http handlers --- transport/http/http.go | 2 ++ transport/http/options.go | 23 +++++++++++++++++++++++ transport/http_transport.go | 12 ++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 transport/http/options.go diff --git a/transport/http/http.go b/transport/http/http.go index bafc0bb3..672db54c 100644 --- a/transport/http/http.go +++ b/transport/http/http.go @@ -1,9 +1,11 @@ +// Package http returns a http2 transport using net/http package http import ( "github.com/micro/go-micro/transport" ) +// NewTransport returns a new http transport using net/http and supporting http2 func NewTransport(opts ...transport.Option) transport.Transport { return transport.NewTransport(opts...) } diff --git a/transport/http/options.go b/transport/http/options.go new file mode 100644 index 00000000..2a6e56c5 --- /dev/null +++ b/transport/http/options.go @@ -0,0 +1,23 @@ +package http + +import ( + "context" + "net/http" + + "github.com/micro/go-micro/transport" +) + +// Handle registers the handler for the given pattern. +func Handle(pattern string, handler http.Handler) transport.Option { + return func(o *transport.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/transport/http_transport.go b/transport/http_transport.go index 514287b7..76eb6318 100644 --- a/transport/http_transport.go +++ b/transport/http_transport.go @@ -357,6 +357,8 @@ func (h *httpTransportListener) Close() error { func (h *httpTransportListener) Accept(fn func(Socket)) error { // create handler mux mux := http.NewServeMux() + + // register our transport handler mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var buf *bufio.ReadWriter var con net.Conn @@ -403,6 +405,16 @@ func (h *httpTransportListener) Accept(fn func(Socket)) error { }) }) + // get optional handlers + if h.ht.opts.Context != nil { + handlers, ok := h.ht.opts.Context.Value("http_handlers").(map[string]http.Handler) + if ok { + for pattern, handler := range handlers { + mux.Handle(pattern, handler) + } + } + } + // default http2 server srv := &http.Server{ Handler: mux,