Exemple #1
0
func (h *JQHandler) handleJqPost(c *gin.Context) {
	if size, err := h.checkReqSize(c); err != nil {
		h.logger(c).WithField("size", size).WithError(err).Info("req too large")
		c.String(http.StatusExpectationFailed, err.Error())
		return
	}

	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, JSONPayloadLimit)

	var j *jq.JQ
	if err := c.BindJSON(&j); err != nil {
		err = fmt.Errorf("error parsing JSON: %s", err)
		h.logger(c).WithError(err).Info("error parsing JSON")
		c.String(http.StatusUnprocessableEntity, err.Error())
		return
	}

	ctx, cancel := context.WithTimeout(c.Request.Context(), JQExecTimeout)
	defer cancel()

	// Evaling into ResponseWriter sets the status code to 200
	// appending error message in the end if there's any
	var debug bytes.Buffer
	w := io.MultiWriter(c.Writer, &debug)
	if err := j.Eval(ctx, w); err != nil {
		fmt.Fprint(c.Writer, err.Error())

		if shouldLogJQError(err) {
			h.logger(c).WithError(err).WithFields(log.Fields{
				"j": j.J,
				"q": j.Q,
				"o": j.Opts(),
				"r": debug.String(),
			}).Info("jq error")
		}
	}
}