From c1e0ce26b57c8d7bb5f355c373456a45f493de3c Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Wed, 14 Jul 2021 13:43:45 +0300 Subject: [PATCH] add ability to register RPC endpoint Signed-off-by: Vasiliy Tolstov --- handler.go | 1 + http.go | 24 ++++++++++++++++++++++++ options.go | 7 +++++++ 3 files changed, 32 insertions(+) diff --git a/handler.go b/handler.go index 102cf13..506383a 100644 --- a/handler.go +++ b/handler.go @@ -123,6 +123,7 @@ func (h *httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { var match bool var hldr patHandler var handler *httpHandler + for _, hpat := range h.handlers { handlertmp := hpat.(*httpHandler) for _, hldrtmp := range handlertmp.handlers[r.Method] { diff --git a/http.go b/http.go index 2e31f4d..e36b80c 100644 --- a/http.go +++ b/http.go @@ -33,6 +33,7 @@ type httpServer struct { pathHandlers map[*regexp.Regexp]http.HandlerFunc contentTypeHandlers map[string]http.HandlerFunc opts server.Options + registerRPC bool sync.RWMutex registered bool init bool @@ -80,6 +81,11 @@ func (h *httpServer) Init(opts ...server.Option) error { if h.contentTypeHandlers == nil { h.contentTypeHandlers = make(map[string]http.HandlerFunc) } + + if v, ok := h.opts.Context.Value(registerRPCHandlerKey{}).(bool); ok { + h.registerRPC = v + } + if phs, ok := h.opts.Context.Value(pathHandlerKey{}).(*pathHandlerVal); ok && phs.h != nil { for pp, ph := range phs.h { exp, err := regexp.Compile(pp) @@ -240,6 +246,24 @@ func (h *httpServer) NewHandler(handler interface{}, opts ...server.HandlerOptio pth := patHandler{pat: pat, mtype: mtype, name: name, rcvr: rcvr} hdlr.name = name hdlr.handlers[md["Method"]] = append(hdlr.handlers[md["Method"]], pth) + + if !h.registerRPC { + continue + } + + cmp, err = rutil.Parse("/" + hn) + if err != nil && h.opts.Logger.V(logger.ErrorLevel) { + h.opts.Logger.Errorf(h.opts.Context, "parsing path pattern err: %v", err) + continue + } + tpl = cmp.Compile() + pat, err = rutil.NewPattern(tpl.Version, tpl.OpCodes, tpl.Pool, tpl.Verb) + if err != nil && h.opts.Logger.V(logger.ErrorLevel) { + h.opts.Logger.Errorf(h.opts.Context, "creating new pattern err: %v", err) + continue + } + pth = patHandler{pat: pat, mtype: mtype, name: name, rcvr: rcvr} + hdlr.handlers[http.MethodPost] = append(hdlr.handlers[http.MethodPost], pth) } return hdlr diff --git a/options.go b/options.go index 4173e5a..7b01d5c 100644 --- a/options.go +++ b/options.go @@ -110,3 +110,10 @@ func ContentTypeHandler(ct string, h http.HandlerFunc) server.Option { o.Context = context.WithValue(o.Context, contentTypeHandlerKey{}, v) } } + +type registerRPCHandlerKey struct{} + +// RegisterRPCHandler registers compatibility endpoints with /ServiceName.ServiceEndpoint method POST +func RegisterRPCHandler(b bool) server.Option { + return server.SetOption(registerRPCHandlerKey{}, b) +}