add cors option

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
2024-03-18 14:51:40 +03:00
parent 74bb12e75e
commit b871c1be38
4 changed files with 1419 additions and 8 deletions

12
http.go
View File

@@ -35,6 +35,7 @@ type Server struct {
pathHandlers *rhttp.Trie
opts server.Options
registerRPC bool
registerCORS bool
sync.RWMutex
registered bool
init bool
@@ -84,6 +85,10 @@ func (h *Server) Init(opts ...server.Option) error {
h.registerRPC = v
}
if v, ok := h.opts.Context.Value(registerCORSHandlerKey{}).(bool); ok {
h.registerCORS = v
}
if phs, ok := h.opts.Context.Value(pathHandlerKey{}).(*pathHandlerVal); ok && phs.h != nil {
for pm, ps := range phs.h {
for pp, ph := range ps {
@@ -227,6 +232,13 @@ func (h *Server) NewHandler(handler interface{}, opts ...server.HandlerOption) s
h.opts.Logger.Errorf(h.opts.Context, "cant add handler for %s %s", md["Method"], md["Path"])
}
if h.registerCORS {
h.opts.Logger.Infof(h.opts.Context, "register cors handler for http.MethodOptions %s /%s", hn, hn)
if err := hdlr.handlers.Insert([]string{http.MethodOptions}, "/"+hn, pth); err != nil {
h.opts.Logger.Errorf(h.opts.Context, "cant add rpc handler for http.MethodOptions %s /%s", hn, hn)
}
}
if h.registerRPC {
h.opts.Logger.Infof(h.opts.Context, "register rpc handler for http.MethodPost %s /%s", hn, hn)
if err := hdlr.handlers.Insert([]string{http.MethodPost}, "/"+hn, pth); err != nil {