// handlePostSource is the HTTP handler for the POST /api/v2/sources route.
487498
func (h *SourceHandler) handlePostSource(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

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

	if err := h.SourceService.CreateSource(ctx, req.Source); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	res := newSourceResponse(req.Source)

	if err := encodeResponse(ctx, w, http.StatusCreated, res); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
463653
func (m *Messenger) HandlePostBack(f PostBackHandler) {
	m.postBackHandlers = append(m.postBackHandlers, f)
}
541190
func (h *DocumentHandler) handlePostDocument(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePostDocumentRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}
	s, err := h.DocumentService.FindDocumentStore(ctx, req.Namespace)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	a, err := pcontext.GetAuthorizer(ctx)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	opts := []influxdb.DocumentOptions{}
	if req.OrgID.Valid() {
		opts = append(opts, influxdb.AuthorizedWithOrgID(a, req.OrgID))
	} else {
		opts = append(opts, influxdb.AuthorizedWithOrg(a, req.Org))
	}
	for _, label := range req.Labels {
		// TODO(desa): make these AuthorizedWithLabel eventually
		opts = append(opts, influxdb.WithLabel(label))
	}

	if err := s.CreateDocument(ctx, req.Document, opts...); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, newDocumentResponse(req.Namespace, req.Document)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
887356
func (h *Client) DataSource(dataSource string) *Client {
	h.dataSource = dataSource
	h.dataSourceSet = true
	return h
}
1369726
func (r *Router) POST(route string, handler interface{}) *Router {
	r.Handle(MethodPOST, route, handler)
	return r
}
1220750
func (h *Handler) handlePostField(w http.ResponseWriter, r *http.Request) {
	if !validHeaderAcceptJSON(r.Header) {
		http.Error(w, "JSON only acceptable response", http.StatusNotAcceptable)
		return
	}
	indexName := mux.Vars(r)["index"]
	fieldName := mux.Vars(r)["field"]

	resp := successResponse{h: h}

	// Decode request.
	var req postFieldRequest
	dec := json.NewDecoder(r.Body)
	dec.DisallowUnknownFields()
	err := dec.Decode(&req)
	if err != nil && err != io.EOF {
		resp.write(w, err)
		return
	}

	// Validate field options.
	if err := req.Options.validate(); err != nil {
		resp.write(w, err)
		return
	}

	// Convert json options into functional options.
	var fos []pilosa.FieldOption
	switch req.Options.Type {
	case pilosa.FieldTypeSet:
		fos = append(fos, pilosa.OptFieldTypeSet(*req.Options.CacheType, *req.Options.CacheSize))
	case pilosa.FieldTypeInt:
		fos = append(fos, pilosa.OptFieldTypeInt(*req.Options.Min, *req.Options.Max))
	case pilosa.FieldTypeTime:
		fos = append(fos, pilosa.OptFieldTypeTime(*req.Options.TimeQuantum, req.Options.NoStandardView))
	case pilosa.FieldTypeMutex:
		fos = append(fos, pilosa.OptFieldTypeMutex(*req.Options.CacheType, *req.Options.CacheSize))
	case pilosa.FieldTypeBool:
		fos = append(fos, pilosa.OptFieldTypeBool())
	}
	if req.Options.Keys != nil {
		if *req.Options.Keys {
			fos = append(fos, pilosa.OptFieldKeys())
		}
	}

	_, err = h.api.CreateField(r.Context(), indexName, fieldName, fos...)
	resp.write(w, err)
}
1060126
func (c *Config) TokenSource(token *oauth2.Token) oauth2.TokenSource {
	config := c.getConfig()
	return config.TokenSource(c.getContext(), token)
}
429680
func (h *postArgsHandler) Handle(
	ctx types.Context,
	w http.ResponseWriter,
	req *http.Request,
	store types.Store) error {

	reqObj := ctx.Value("reqObj")
	if reqObj == nil {
		return fmt.Errorf("missing request object")
	}

	v := reflect.ValueOf(reqObj).Elem()
	t := v.Type()

	for i := 0; i < v.NumField(); i++ {
		ft := t.Field(i)
		fv := v.Field(i).Interface()

		switch tfv := fv.(type) {
		case nil:
			// do nothing
		case map[string]interface{}:
			store.Set(getFieldName(ft), utils.NewStoreWithData(tfv))
		default:
			// add it to the store
			store.Set(getFieldName(ft), fv)
		}
	}

	if h.config.GetBool(types.ConfigServerParseRequestOpts) {
		ctx.Debug("parsing req opts enabled")
		if store.IsSet("opts") {
			ctx.Debug("parsing req opts: is set")
			if opts, ok := store.Get("opts").(types.Store); ok {
				ctx.Debug("parsing req opts: valid type")
				for _, k := range opts.Keys() {
					store.Set(k, opts.Get(k))
					ctx.WithField("optsKey", k).Debug(
						"parsing req opts: set key")
				}
			}
		}
	}

	return h.handler(ctx, w, req, store)
}
723857
func PostProcessRecordMatchResponse() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		logger.Log.Info("PostProcessRecordMatchResponse: Before calling handler")
		ctx.Next()
		resourceType, _ := ctx.Get("Resource")

		logger.Log.WithFields(logrus.Fields{"action": "check resource type exists",
			"method":       ctx.Request.Method,
			"query":        ctx.Request.RequestURI,
			"resourceType": resourceType}).Info("PostProcessRecordMatchResponse")

		if resourceType.(string) == "Bundle" &&
			ctx.Request.Method == "PUT" || ctx.Request.Method == "POST" {
			resource, _ := ctx.Get(resourceType.(string))
			// Need to access Database via global variable 'cuz DB not initializaed when middlewhare is configured
			updateRecordMatchRun(fhir_svr.Database, resource.(*fhir_models.Bundle))
		}
	}

}
848041
func (h *QueryHandler) handlePostQuery(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	var req query.Request
	req.WithCompilerMappings(h.CompilerMappings)
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	results, err := h.QueryService.Query(ctx, &req)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}
	// Always cancel the results to free resources.
	// If all results were consumed cancelling does nothing.
	defer results.Release()

	// Setup headers
	stats, hasStats := results.(flux.Statisticser)
	if hasStats {
		w.Header().Set("Trailer", queryStatisticsTrailer)
	}

	// NOTE: We do not write out the headers here.
	// It is possible that if the encoding step fails
	// that we can write an error header so long as
	// the encoder did not write anything.
	// As such we rely on the http.ResponseWriter behavior
	// to write an StatusOK header with the first write.

	switch r.Header.Get("Accept") {
	case "text/csv":
		fallthrough
	default:
		h.csvDialect.SetHeaders(w)
		encoder := h.csvDialect.Encoder()
		n, err := encoder.Encode(w, results)
		if err != nil {
			if n == 0 {
				// If the encoder did not write anything, we can write an error header.
				EncodeError(ctx, err, w)
			} else {
				h.Logger.Info("Failed to encode client response",
					zap.Error(err),
				)
			}
		}
	}

	if hasStats {
		data, err := json.Marshal(stats.Statistics())
		if err != nil {
			h.Logger.Info("Failed to encode statistics", zap.Error(err))
			return
		}
		// Write statisitcs trailer
		w.Header().Set(queryStatisticsTrailer, string(data))
	}
}
458025
func (r *Route) PostFunc(f http.HandlerFunc) *Route {
	return r.Post(http.HandlerFunc(f))
}
454140
func (h *Handler) handlePostFieldAttrDiff(w http.ResponseWriter, r *http.Request) {
	if !validHeaderAcceptJSON(r.Header) {
		http.Error(w, "JSON only acceptable response", http.StatusNotAcceptable)
		return
	}
	indexName := mux.Vars(r)["index"]
	fieldName := mux.Vars(r)["field"]

	// Decode request.
	var req postFieldAttrDiffRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	attrs, err := h.api.FieldAttrDiff(r.Context(), indexName, fieldName, req.Blocks)
	if err != nil {
		switch errors.Cause(err) {
		case pilosa.ErrFragmentNotFound:
			http.Error(w, err.Error(), http.StatusNotFound)
		default:
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		return
	}

	// Encode response.
	if err := json.NewEncoder(w).Encode(postFieldAttrDiffResponse{
		Attrs: attrs,
	}); err != nil {
		h.logger.Printf("response encoding error: %s", err)
	}
}
1288458
func (h *UserHandler) handlePostUser(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

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

	if err := h.UserService.CreateUser(ctx, req.User); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, newUserResponse(req.User)); err != nil {
		EncodeError(ctx, err, w)
		return
	}
}
391317
func (s *SearchSource) Source() interface{} {
	source := make(map[string]interface{})

	if s.from != -1 {
		source["from"] = s.from
	}
	if s.size != -1 {
		source["size"] = s.size
	}
	if s.timeout != "" {
		source["timeout"] = s.timeout
	}
	if s.query != nil {
		source["query"] = s.query.Source()
	}
	if s.postFilter != nil {
		source["post_filter"] = s.postFilter.Source()
	}
	if s.minScore != nil {
		source["min_score"] = *s.minScore
	}
	if s.version != nil {
		source["version"] = *s.version
	}
	if s.explain != nil {
		source["explain"] = *s.explain
	}
	if s.fetchSourceContext != nil {
		source["_source"] = s.fetchSourceContext.Source()
	}

	if s.fieldNames != nil {
		switch len(s.fieldNames) {
		case 1:
			source["fields"] = s.fieldNames[0]
		default:
			source["fields"] = s.fieldNames
		}
	}

	if len(s.fieldDataFields) > 0 {
		source["fielddata_fields"] = s.fieldDataFields
	}

	if len(s.partialFields) > 0 {
		pfmap := make(map[string]interface{})
		for _, partialField := range s.partialFields {
			pfmap[partialField.Name] = partialField.Source()
		}
		source["partial_fields"] = pfmap
	}

	if len(s.scriptFields) > 0 {
		sfmap := make(map[string]interface{})
		for _, scriptField := range s.scriptFields {
			sfmap[scriptField.FieldName] = scriptField.Source()
		}
		source["script_fields"] = sfmap
	}

	if len(s.sorters) > 0 {
		sortarr := make([]interface{}, 0)
		for _, sorter := range s.sorters {
			sortarr = append(sortarr, sorter.Source())
		}
		source["sort"] = sortarr
	} else if len(s.sorts) > 0 {
		sortarr := make([]interface{}, 0)
		for _, sort := range s.sorts {
			sortarr = append(sortarr, sort.Source())
		}
		source["sort"] = sortarr
	}

	if s.trackScores {
		source["track_scores"] = s.trackScores
	}

	if len(s.indexBoosts) > 0 {
		source["indices_boost"] = s.indexBoosts
	}

	if len(s.facets) > 0 {
		facetsMap := make(map[string]interface{})
		for field, facet := range s.facets {
			facetsMap[field] = facet.Source()
		}
		source["facets"] = facetsMap
	}

	if len(s.aggregations) > 0 {
		aggsMap := make(map[string]interface{})
		for name, aggregate := range s.aggregations {
			aggsMap[name] = aggregate.Source()
		}
		source["aggregations"] = aggsMap
	}

	if s.highlight != nil {
		source["highlight"] = s.highlight.Source()
	}

	if len(s.suggesters) > 0 {
		suggesters := make(map[string]interface{})
		for _, s := range s.suggesters {
			suggesters[s.Name()] = s.Source(false)
		}
		if s.globalSuggestText != "" {
			suggesters["text"] = s.globalSuggestText
		}
		source["suggest"] = suggesters
	}

	if len(s.rescores) > 0 {
		// Strip empty rescores from request
		rescores := make([]*Rescore, 0)
		for _, r := range s.rescores {
			if !r.IsEmpty() {
				rescores = append(rescores, r)
			}
		}

		if len(rescores) == 1 {
			rescores[0].defaultRescoreWindowSize = s.defaultRescoreWindowSize
			source["rescore"] = rescores[0].Source()
		} else {
			slice := make([]interface{}, 0)
			for _, r := range rescores {
				r.defaultRescoreWindowSize = s.defaultRescoreWindowSize
				slice = append(slice, r.Source())
			}
			source["rescore"] = slice
		}
	}

	if len(s.stats) > 0 {
		source["stats"] = s.stats
	}

	if len(s.innerHits) > 0 {
		// Top-level inner hits
		// See http://www.elastic.co/guide/en/elasticsearch/reference/1.5/search-request-inner-hits.html#top-level-inner-hits
		// "inner_hits": {
		//   "<inner_hits_name>": {
		//     "<path|type>": {
		//       "<path-to-nested-object-field|child-or-parent-type>": {
		//         <inner_hits_body>,
		//         [,"inner_hits" : { [<sub_inner_hits>]+ } ]?
		//       }
		//     }
		//   },
		//   [,"<inner_hits_name_2>" : { ... } ]*
		// }
		m := make(map[string]interface{})
		for name, hit := range s.innerHits {
			if hit.path != "" {
				path := make(map[string]interface{})
				path[hit.path] = hit.Source()
				m[name] = map[string]interface{}{
					"path": path,
				}
			} else if hit.typ != "" {
				typ := make(map[string]interface{})
				typ[hit.typ] = hit.Source()
				m[name] = map[string]interface{}{
					"type": typ,
				}
			} else {
				// TODO the Java client throws here, because either path or typ must be specified
			}
		}
		source["inner_hits"] = m
	}

	return source
}
776350
func (s *Server) HandlePostRaw(w http.ResponseWriter, r *http.Request) {
	ruid := GetRUID(r.Context())
	log.Debug("handle.post.raw", "ruid", ruid)

	postRawCount.Inc(1)

	toEncrypt := false
	uri := GetURI(r.Context())
	if uri.Addr == "encrypt" {
		toEncrypt = true
	}

	if uri.Path != "" {
		postRawFail.Inc(1)
		respondError(w, r, "raw POST request cannot contain a path", http.StatusBadRequest)
		return
	}

	if uri.Addr != "" && uri.Addr != "encrypt" {
		postRawFail.Inc(1)
		respondError(w, r, "raw POST request addr can only be empty or \"encrypt\"", http.StatusBadRequest)
		return
	}

	if r.Header.Get("Content-Length") == "" {
		postRawFail.Inc(1)
		respondError(w, r, "missing Content-Length header in request", http.StatusBadRequest)
		return
	}

	addr, _, err := s.api.Store(r.Context(), r.Body, r.ContentLength, toEncrypt)
	if err != nil {
		postRawFail.Inc(1)
		respondError(w, r, err.Error(), http.StatusInternalServerError)
		return
	}

	log.Debug("stored content", "ruid", ruid, "key", addr)

	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	fmt.Fprint(w, addr)
}
1024796
func (ns *Namespace) PostCSS(args ...interface{}) (resource.Resource, error) {
	r, m, err := ns.resolveArgs(args)
	if err != nil {
		return nil, err
	}
	var options postcss.Options
	if m != nil {
		options, err = postcss.DecodeOptions(m)
		if err != nil {
			return nil, err
		}
	}

	return ns.postcssClient.Process(r, options)
}
31262
func (s *Server) handlePOST(c *router.Context) {
	serviceName := c.Params.ByName("service")
	methodName := c.Params.ByName("method")
	s.setAccessControlHeaders(c, false)
	res := s.call(c, serviceName, methodName)
	if res.err != nil {
		writeError(c.Context, c.Writer, res.err)
		return
	}
	writeMessage(c.Context, c.Writer, res.out, res.fmt)
}