Exemplo n.º 1
0
// UnmarshalFromBody - Unmarshals component from request bodyCompileInContext() on certain methods.
// Stores result in context to be retrieved with `components.FromContext`.
func UnmarshalFromBody(methods ...string) middlewares.Handler {
	return middlewares.ToHandler(func(ctx context.Context, w http.ResponseWriter, r *http.Request, next xhandler.HandlerC) {
		if !helpers.Contain(methods, r.Method) {
			next.ServeHTTPC(ctx, w, r)
			return
		}
		c := new(components.Component)
		err := json.NewDecoder(r.Body).Decode(c)
		if err != nil {
			helpers.WriteError(w, r, http.StatusBadRequest, err.Error())
			return
		}
		ctx = components.NewContext(ctx, c)
		next.ServeHTTPC(ctx, w, r)
	})
}
Exemplo n.º 2
0
// UnmarshalFromQuery - Unmarshals component from `json` query on certain methods.
// Stores result in context to be retrieved with `components.FromContext`.
func UnmarshalFromQuery(methods ...string) middlewares.Handler {
	return middlewares.ToHandler(func(ctx context.Context, w http.ResponseWriter, r *http.Request, next xhandler.HandlerC) {
		if len(methods) != 0 && !helpers.Contain(methods, r.Method) {
			next.ServeHTTPC(ctx, w, r)
			return
		}

		// Read component from request
		c, err := readComponent(r)
		if err != nil {
			helpers.WriteError(w, r, http.StatusBadRequest, err.Error())
			return
		}

		// Create a context with component and move to next handler
		ctx = components.NewContext(ctx, c)
		next.ServeHTTPC(ctx, w, r)
	})
}