// handlePostQuery handles query requests.
168152
func (h *ProxyQueryHandler) handlePostQuery(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	var req query.ProxyRequest
	req.WithCompilerMappings(h.CompilerMappings)
	req.WithDialectMappings(h.DialectMappings)
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	hd, ok := req.Dialect.(HTTPDialect)
	if !ok {
		EncodeError(ctx, fmt.Errorf("unsupported dialect over HTTP %T", req.Dialect), w)
		return
	}
	hd.SetHeaders(w)

	n, err := h.ProxyQueryService.Query(ctx, w, &req)
	if err != nil {
		if n == 0 {
			// Only record the error headers IFF nothing has been written to w.
			EncodeError(ctx, err, w)
			return
		}
		h.Logger.Info("Error writing response to client",
			zap.String("handler", "transpilerde"),
			zap.Error(err),
		)
	}
}
691423
func handleMatch(c *gin.Context) {
	type QueryJSON struct {
		SearchString string `json:"s"`
		N            int    `json:"n"`
	}
	var json QueryJSON
	if c.BindJSON(&json) != nil {
		log.Trace("Got %v", json)
		c.String(http.StatusBadRequest, "Must provide search_string")
		return
	}
	log.Trace("Got %v", json)
	if json.N == 0 {
		c.JSON(http.StatusOK, gin.H{"r": cm.Closest(json.SearchString)})
	} else {
		c.JSON(http.StatusOK, gin.H{"r": cm.ClosestN(json.SearchString, json.N)})
	}
}
1150876
func (s *Service) handleQuery(connID uint64, w http.ResponseWriter, r *http.Request) {
	isAtomic, err := isAtomic(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	timings, err := timings(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	lvl, err := level(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Get the query statement(s), and do tx if necessary.
	queries, err := requestQueries(r)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// Get the right queryer object.
	var queryer Queryer
	if connID == defaultConnID {
		queryer = s.store
	} else {
		c, ok := s.store.Connection(connID)
		if !ok {
			http.Error(w, "connection not found", http.StatusNotFound)
			return
		}
		queryer = c
	}

	var resp Response
	results, err := queryer.Query(&store.QueryRequest{queries, timings, isAtomic, lvl})
	if err != nil {
		if err == store.ErrNotLeader {
			leader := s.leaderAPIAddr()
			if leader == "" {
				http.Error(w, err.Error(), http.StatusServiceUnavailable)
				return
			}

			redirect := s.FormRedirect(r, leader)
			http.Redirect(w, r, redirect, http.StatusMovedPermanently)
			return
		}
		resp.Error = err.Error()
	} else {
		resp.Results = results.Rows
		if timings {
			resp.Time = results.Time
		}
		resp.Raft = results.Raft
	}
	writeResponse(w, r, &resp)
}
178481
func (h *AuthorizationHandler) handlePostAuthorization(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePostAuthorizationRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	user, err := getAuthorizedUser(r, h.UserService)
	if err != nil {
		EncodeError(ctx, platform.ErrUnableToCreateToken, w)
		return
	}

	auth := req.toPlatform(user.ID)

	org, err := h.OrganizationService.FindOrganizationByID(ctx, auth.OrgID)
	if err != nil {
		EncodeError(ctx, platform.ErrUnableToCreateToken, w)
		return
	}

	if err := h.AuthorizationService.CreateAuthorization(ctx, auth); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	perms, err := newPermissionsResponse(ctx, auth.Permissions, h.LookupService)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, newAuthResponse(auth, org, user, perms)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
857566
func (h *ProxyQueryHandler) handlePing(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusNoContent)
}
829640
func (a *Handler) handleSearch(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		camhttputil.BadRequestError(w, camhttputil.InvalidMethodError{}.Error())
		return
	}
	if a.sh == nil {
		http.Error(w, "app proxy has no search handler", 500)
		return
	}
	a.masterQueryMu.RLock()
	if a.masterQuery == nil {
		http.Error(w, "search is not allowed", http.StatusForbidden)
		a.masterQueryMu.RUnlock()
		return
	}
	a.masterQueryMu.RUnlock()
	var sq search.SearchQuery
	if err := sq.FromHTTP(r); err != nil {
		camhttputil.ServeJSONError(w, err)
		return
	}
	sr, err := a.sh.Query(r.Context(), &sq)
	if err != nil {
		camhttputil.ServeJSONError(w, err)
		return
	}
	// check this search is in the allowed domain
	if !a.allowProxySearchResponse(sr) {
		// there's a chance our domainBlobs cache is expired so let's
		// refresh it and retry, but no more than once per minute.
		if err := a.refreshDomainBlobs(); err != nil {
			http.Error(w, "search scope is forbidden", http.StatusForbidden)
			return
		}
		if !a.allowProxySearchResponse(sr) {
			http.Error(w, "search scope is forbidden", http.StatusForbidden)
			return
		}
	}
	camhttputil.ReturnJSON(w, sr)
}
886310
func NewQueryHandler() *QueryHandler {
	h := &QueryHandler{
		Router: NewRouter(),
		csvDialect: csv.Dialect{
			ResultEncoderConfig: csv.DefaultEncoderConfig(),
		},
	}

	h.HandlerFunc("GET", "/ping", h.handlePing)
	h.HandlerFunc("POST", queryPath, h.handlePostQuery)
	return h
}
365523
func ContainerChildrenPostQuery(
	ctx context.Context,
	client api.Client,
	containerPath string,
	limit, maxDepth int,
	query *ContainerQuery) ([]*ContainerChild, error) {

	var resp ContainerChildList

	if err := client.Post(
		ctx,
		realNamespacePath(client),
		containerPath,
		api.OrderedValues{
			{queryByteArr},
			{limitByteArr, []byte(fmt.Sprintf("%d", limit))},
			{maxDepthByteArr, []byte(fmt.Sprintf("%d", maxDepth))},
		},
		nil,
		query,
		&resp); err != nil {

		return nil, err
	}

	return resp, nil
}
383821
func (raw *Raw) Query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error) {
	return raw.c.query(endpoint, out, q)
}
1224537
func (c *Client) handleOpen() error {
	if c.hasCredentials() {
		err_auth := c.authenticate(context.Background())
		if err_auth != nil {
			return err_auth
		}
	} else {
		c.checkResubscription()
	}
	return nil
}
1342031
func (res *Resource) postHandler(w http.ResponseWriter, r *http.Request, storage store.Save) {
	parsedObject, parseErr := jsh.ParseObject(r)
	if parseErr != nil && reflect.ValueOf(parseErr).IsNil() == false {
		SendHandler(w, r, parseErr)
		return
	}

	object, err := storage(r.Context(), parsedObject)
	if err != nil && reflect.ValueOf(err).IsNil() == false {
		SendHandler(w, r, err)
		return
	}

	SendHandler(w, r, object)
}
1198418
func (h *guiArchiveHandler) handlePost(w http.ResponseWriter, req *http.Request) error {
	// Validate the request.
	if ctype := req.Header.Get("Content-Type"); ctype != bzMimeType {
		return errors.BadRequestf("invalid content type %q: expected %q", ctype, bzMimeType)
	}
	if err := req.ParseForm(); err != nil {
		return errors.Annotate(err, "cannot parse form")
	}
	versParam := req.Form.Get("version")
	if versParam == "" {
		return errors.BadRequestf("version parameter not provided")
	}
	vers, err := version.Parse(versParam)
	if err != nil {
		return errors.BadRequestf("invalid version parameter %q", versParam)
	}
	hashParam := req.Form.Get("hash")
	if hashParam == "" {
		return errors.BadRequestf("hash parameter not provided")
	}
	if req.ContentLength == -1 {
		return errors.BadRequestf("content length not provided")
	}

	// Open the GUI archive storage.
	st, err := h.ctxt.stateForRequestAuthenticatedUser(req)
	if err != nil {
		return errors.Annotate(err, "cannot open state")
	}
	defer st.Release()
	storage, err := st.GUIStorage()
	if err != nil {
		return errors.Annotate(err, "cannot open GUI storage")
	}
	defer storage.Close()

	// Read and validate the archive data.
	data, hash, err := readAndHash(req.Body)
	size := int64(len(data))
	if size != req.ContentLength {
		return errors.BadRequestf("archive does not match provided content length")
	}
	if hash != hashParam {
		return errors.BadRequestf("archive does not match provided hash")
	}

	// Add the archive to the GUI storage.
	metadata := binarystorage.Metadata{
		Version: vers.String(),
		Size:    size,
		SHA256:  hash,
	}
	if err := storage.Add(bytes.NewReader(data), metadata); err != nil {
		return errors.Annotate(err, "cannot add GUI archive to storage")
	}

	// Prepare and return the response.
	resp := params.GUIArchiveVersion{
		Version: vers,
		SHA256:  hash,
	}
	if currentVers, err := st.GUIVersion(); err == nil {
		if currentVers == vers {
			resp.Current = true
		}
	} else if !errors.IsNotFound(err) {
		return errors.Annotate(err, "cannot retrieve current GUI version")

	}
	return errors.Trace(sendStatusAndJSON(w, http.StatusOK, resp))
}
590701
func (h *Handler) readQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) {
	switch r.Header.Get("Content-Type") {
	case "application/x-protobuf":
		return h.readProtobufQueryRequest(r)
	default:
		return h.readURLQueryRequest(r)
	}
}
647623
func (h *TelegrafHandler) handlePostTelegraf(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	tc, err := decodePostTelegrafRequest(ctx, r)
	if err != nil {
		h.Logger.Debug("failed to decode request", zap.Error(err))
		EncodeError(ctx, err, w)
		return
	}
	auth, err := pctx.GetAuthorizer(ctx)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := h.TelegrafService.CreateTelegrafConfig(ctx, tc, auth.GetUserID()); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, newTelegrafResponse(tc, []*platform.Label{})); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
873096
func NewProxyQueryHandler() *ProxyQueryHandler {
	h := &ProxyQueryHandler{
		Router: NewRouter(),
	}

	h.HandlerFunc("POST", proxyQueryPath, h.handlePostQuery)
	return h
}
133168
func (c *Connection) sendQuery(q Query) error {
	buf := &bytes.Buffer{}
	buf.Grow(respHeaderLen)
	buf.Write(buf.Bytes()[:respHeaderLen]) // reserve for header
	enc := json.NewEncoder(buf)

	// Build query
	err := enc.Encode(q.Build())
	if err != nil {
		return RQLDriverError{rqlError(fmt.Sprintf("Error building query: %s", err.Error()))}
	}

	b := buf.Bytes()

	// Write header
	binary.LittleEndian.PutUint64(b, uint64(q.Token))
	binary.LittleEndian.PutUint32(b[8:], uint32(len(b)-respHeaderLen))

	// Set timeout
	if c.opts.WriteTimeout != 0 {
		c.Conn.SetWriteDeadline(time.Now().Add(c.opts.WriteTimeout))
	}

	// Send the JSON encoding of the query itself.
	if err = c.writeData(b); err != nil {
		c.setBad()
		return RQLConnectionError{rqlError(err.Error())}
	}

	return nil
}
876153
func (s *serfQueries) handleConflict(q *Query) {
	// The target node name is the payload
	node := string(q.Payload)

	// Do not respond to the query if it is about us
	if node == s.serf.config.NodeName {
		return
	}
	s.logger.Printf("[DEBUG] serf: Got conflict resolution query for '%s'", node)

	// Look for the member info
	var out *Member
	s.serf.memberLock.Lock()
	if member, ok := s.serf.members[node]; ok {
		out = &member.Member
	}
	s.serf.memberLock.Unlock()

	// Encode the response
	buf, err := encodeMessage(messageConflictResponseType, out)
	if err != nil {
		s.logger.Printf("[ERR] serf: Failed to encode conflict query response: %v", err)
		return
	}

	// Send our answer
	if err := q.Respond(buf); err != nil {
		s.logger.Printf("[ERR] serf: Failed to respond to conflict query: %v", err)
	}
}