Esempio n. 1
0
func init() {
	middlewares.Register(middlewares.Descriptor{
		Name: "my_test_middleware",
		Options: []*options.Option{
			{Name: "opts1", Type: options.TypeString},
		},
	}, func(o middlewares.Options) (middlewares.Handler, error) {
		return middlewares.ToHandler(func(ctx context.Context, w http.ResponseWriter, r *http.Request, next xhandler.HandlerC) {
			ctx = components.WithTemplateKey(ctx, "some1", "test1")
			ctx = components.WithTemplateKey(ctx, "some2", "test2")
			next.ServeHTTPC(ctx, w, r)
		}), nil
	})
}
Esempio n. 2
0
func middlewareByName(opts Options) (Handler, error) {
	descriptors := Descriptors()
	sort.Sort(byName(descriptors))

	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			name, err := opts.String(ctx, optMiddlewareName)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			reskey, _ := opts.String(ctx, optMiddlewareDestination)

			for _, desc := range descriptors {
				if desc.Name == name {
					ctx = components.WithTemplateKey(ctx, reskey, desc)
					break
				}
			}

			next.ServeHTTPC(ctx, w, r)
		})
	}, nil
}
Esempio n. 3
0
func middlewaresList(opts Options) (Handler, error) {
	descriptors := Descriptors()
	sort.Sort(byName(descriptors))

	return func(next xhandler.HandlerC) xhandler.HandlerC {
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			reskey, _ := opts.String(ctx, optMiddlewaresDestination)
			ctx = components.WithTemplateKey(ctx, reskey, descriptors)
			next.ServeHTTPC(ctx, w, r)
		})
	}, nil
}
Esempio n. 4
0
		middleware, err := middlewares.Construct(md)
		if err != nil {
			return nil, err
		}
		if tracing {
			middleware = tracingMiddleware(md, middleware)
		}
		opts = append(opts, WithMiddleware(middleware))
	}

	return New(opts...), nil
}

var initMiddleware = middlewares.ToHandler(func(ctx context.Context, w http.ResponseWriter, r *http.Request, next xhandler.HandlerC) {
	ctx = NewRequestContext(ctx, r)
	ctx = components.WithTemplateKey(ctx, "request", r)
	ctx = components.WithTemplateKey(ctx, "params", xmux.Params(ctx))
	next.ServeHTTPC(ctx, w, r)
})

// tracingMiddleware - Tracing for middlewares.
func tracingMiddleware(md *middlewares.Middleware, handler middlewares.Handler) middlewares.Handler {
	return func(next xhandler.HandlerC) xhandler.HandlerC {
		h := handler(next)
		return xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			tr, _ := trace.FromContext(ctx)
			tr.LazyPrintf("%s", md.Name)
			h.ServeHTTPC(ctx, w, r)
		})
	}
}