// Handler apply the CORS specification on the request, and add relevant CORS headers
// as necessary.
499680
func (c *Cors) Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
			c.logf("Handler: Preflight request")
			c.handlePreflight(w, r)
			// Preflight requests are standalone and should stop the chain as some other
			// middleware may not handle OPTIONS requests correctly. One typical example
			// is authentication middleware ; OPTIONS requests won't carry authentication
			// headers (see #1)
			if c.optionPassthrough {
				h.ServeHTTP(w, r)
			} else {
				w.WriteHeader(http.StatusOK)
			}
		} else {
			c.logf("Handler: Actual request")
			c.handleActualRequest(w, r)
			h.ServeHTTP(w, r)
		}
	})
}
1105936
func (d *SUIData3) Handler(notFound http.Handler, defaultDef string) http.Handler {
	return suihttp.Handler(d.as, notFound, d.index, d.def, defaultDef)
}
196460
func (cg *CertGeneratorHandler) Handle(w http.ResponseWriter, r *http.Request) error {
	log.Info("request for CSR")

	req := new(genSignRequest)
	req.Request = csr.New()

	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warningf("failed to read request body: %v", err)
		return errors.NewBadRequest(err)
	}
	r.Body.Close()

	err = json.Unmarshal(body, req)
	if err != nil {
		log.Warningf("failed to unmarshal request: %v", err)
		return errors.NewBadRequest(err)
	}

	if req.Request == nil {
		log.Warning("empty request received")
		return errors.NewBadRequestString("missing request section")
	}

	if req.Request.CA != nil {
		log.Warningf("request received with CA section")
		return errors.NewBadRequestString("ca section only permitted in initca")
	}

	csr, key, err := cg.generator.ProcessRequest(req.Request)
	if err != nil {
		log.Warningf("failed to process CSR: %v", err)
		// The validator returns a *cfssl/errors.HttpError
		return err
	}

	signReq := signer.SignRequest{
		Request: string(csr),
		Profile: req.Profile,
		Label:   req.Label,
	}

	certBytes, err := cg.signer.Sign(signReq)
	if err != nil {
		log.Warningf("failed to sign request: %v", err)
		return err
	}

	reqSum, err := computeSum(csr)
	if err != nil {
		return errors.NewBadRequest(err)
	}

	certSum, err := computeSum(certBytes)
	if err != nil {
		return errors.NewBadRequest(err)
	}

	result := map[string]interface{}{
		"private_key":         string(key),
		"certificate_request": string(csr),
		"certificate":         string(certBytes),
		"sums": map[string]Sum{
			"certificate_request": reqSum,
			"certificate":         certSum,
		},
	}

	if req.Bundle {
		if cg.bundler == nil {
			return api.SendResponseWithMessage(w, result, NoBundlerMessage,
				errors.New(errors.PolicyError, errors.InvalidRequest).ErrorCode)
		}

		bundle, err := cg.bundler.BundleFromPEMorDER(certBytes, nil, bundler.Optimal, "")
		if err != nil {
			return err
		}

		result["bundle"] = bundle
	}

	if len(req.Request.Hosts) == 0 {
		return api.SendResponseWithMessage(w, result, CSRNoHostMessage,
			errors.New(errors.PolicyError, errors.InvalidRequest).ErrorCode)
	}

	return api.SendResponse(w, result)
}
697546
func CORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Set allow origin to match origin of our request or fall back to *
		if o := r.Header.Get(origin); o != "" {
			w.Header().Set(allow_origin, o)
		} else {
			w.Header().Set(allow_origin, "*")
		}

		// Set other headers
		w.Header().Set(allow_headers, headers)
		w.Header().Set(allow_methods, methods)
		w.Header().Set(allow_credentials, credentials)
		w.Header().Set(expose_headers, headers)

		// If this was preflight options request let's write empty ok response and return
		if r.Method == options {
			w.WriteHeader(http.StatusOK)
			w.Write(nil)
			return
		}

		next.ServeHTTP(w, r)
	})
}
630003
func (_m *Router) Handler() http.Handler {
	ret := _m.Called()

	var r0 http.Handler
	if rf, ok := ret.Get(0).(func() http.Handler); ok {
		r0 = rf()
	} else {
		r0 = ret.Get(0).(http.Handler)
	}

	return r0
}
128904
func (middleware *Middleware) Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		context, err := middleware.Limiter.Get(r.Context(), middleware.Limiter.GetIPKey(r))
		if err != nil {
			middleware.OnError(w, r, err)
			return
		}

		w.Header().Add("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10))
		w.Header().Add("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10))
		w.Header().Add("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10))

		if context.Reached {
			middleware.OnLimitReached(w, r)
			return
		}

		h.ServeHTTP(w, r)
	})
}
813033
func (c Chain) Handler(xh HandlerC) http.Handler {
	ctx := context.Background()
	return c.HandlerCtx(ctx, xh)
}
1127221
func (p *PushGateway) Handler(w http.ResponseWriter, r *http.Request) {
	// redirect to agreement to give our users information about
	// this collected data.
	switch r.Method {
	case http.MethodGet, http.MethodHead:
		http.Redirect(w, r, "https://www.influxdata.com/telemetry", http.StatusSeeOther)
		return
	case http.MethodPost, http.MethodPut:
	default:
		w.Header().Set("Allow", "GET, HEAD, PUT, POST")
		http.Error(w,
			http.StatusText(http.StatusMethodNotAllowed),
			http.StatusMethodNotAllowed,
		)
		return
	}

	if p.Timeout == 0 {
		p.Timeout = DefaultTimeout
	}

	if p.MaxBytes == 0 {
		p.MaxBytes = DefaultMaxBytes
	}

	if p.Encoder == nil {
		p.Encoder = &prometheus.Expfmt{
			Format: expfmt.FmtText,
		}
	}

	ctx, cancel := context.WithTimeout(
		r.Context(),
		p.Timeout,
	)
	defer cancel()

	r = r.WithContext(ctx)
	defer r.Body.Close()

	format, err := metricsFormat(r.Header)
	if err != nil {
		p.Logger.Error("metrics format not support", zap.Error(err))
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	mfs, err := decodePostMetricsRequest(r.Body, format, p.MaxBytes)
	if err != nil {
		p.Logger.Error("unable to decode metrics", zap.Error(err))
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if err := valid(mfs); err != nil {
		p.Logger.Error("invalid metrics", zap.Error(err))
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	for _, transformer := range p.Transformers {
		mfs = transformer.Transform(mfs)
	}

	data, err := p.Encoder.Encode(mfs)
	if err != nil {
		p.Logger.Error("unable to encode metric families", zap.Error(err))
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := p.Store.WriteMessage(ctx, data); err != nil {
		p.Logger.Error("unable to write to store", zap.Error(err))
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusAccepted)
}
253296
func (h *Handler) Handle(err error) {
	var interfaces []raven.Interface

	// Get HTTP request (if any)
	if req, ok := httperr.HTTPRequest(err); ok {
		interfaces = append(interfaces, raven.NewHttp(req))
	}

	packet := raven.NewPacketWithExtra(
		err.Error(),
		keyvals.ToMap(emperror.Context(err)),
		append(
			interfaces,
			raven.NewException(
				err,
				raven.GetOrNewStacktrace(emperror.ExposeStackTrace(err), 1, 3, h.client.IncludePaths()),
			),
		)...,
	)

	eventID, ch := h.client.Capture(packet, nil)

	if h.sendSynchronously && eventID != "" {
		<-ch
	}
}
466996
func (idp *IdentityProvider) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc(idp.MetadataURL.Path, idp.ServeMetadata)
	mux.HandleFunc(idp.SSOURL.Path, idp.ServeSSO)
	return mux
}
45904
func (s *Server) Handle(route string, method string, httpHandler http.Handler) {
	s.addRoute(route, method, httpHandler)
}
98321
func (s *Server) Handle(method string, h http.Handler) {
	s.muHandlers.Lock()
	defer s.muHandlers.Unlock()
	s.handlers[method] = h
}
951921
func (m *Mux) Handler(method, path string, handler http.Handler) {
	m.Handle(method, path, func(w http.ResponseWriter, req *http.Request) {
		handler.ServeHTTP(w, req)
	})
}
240199
func (o *Options) Handler(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		initOnce.Do(func() {
			options = make(map[*http.Request]*Options)
			responded = make(map[*http.Request]bool)
		})
		mutex.Lock()
		options[r] = o
		mutex.Unlock()
		defer func() {
			mutex.Lock()
			delete(options, r)
			delete(responded, r)
			mutex.Unlock()
		}()
		handler.ServeHTTP(w, r)
	})
}
254124
func Cors(allowedOrigins ...string) http.HandlerFunc {
	if len(allowedOrigins) == 0 {
		allowedOrigins = append(allowedOrigins, "*")
	}
	return func(rw http.ResponseWriter, req *http.Request) {
		allowed := false
		// Set appropriate response headers required for CORS
		reqOrigin := req.Header.Get(headerGetOrigin)
		for _, o := range allowedOrigins {
			// Set appropriate response headers required for CORS
			if o == "*" || o == reqOrigin {
				rw.Header().Set(headerOrigin, reqOrigin)
				allowed = true
				break
			}
		}

		if !allowed {
			webgo.SendHeader(rw, http.StatusForbidden)
			return
		}

		rw.Header().Set(headerMethods, allowMethods)
		rw.Header().Set(headerCreds, "true")

		// Adding allowed headers
		rw.Header().Set(headerAllowHeaders, allowHeaders+req.Header.Get(headerReqHeaders))
	}
}
113579
func (mux *Mux) handler() *handler {
	return &handler{
		mux: mux,
		c:   make(chan net.Conn),
	}
}
1241654
func Handler(h http.Handler, opts ...option) http.Handler {
	sh := new(handler)
	sh.name = "hs"
	sh.maxAge = 86400 // 1 day

	for _, opt := range opts {
		opt(sh)
	}

	if len(sh.keys) == 0 {
		panic("session: at least one secret key is required")
	}

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		session, err := sh.Load(r)
		if err != nil {
			http.Error(w, fmt.Sprintf("Internal error: %#v", err), http.StatusInternalServerError)
			return
		}
		ctx := newContext(r.Context(), session)
		res := internal.NewResponseWriter(w)
		res.Before(func(w internal.ResponseWriter) {
			sh.Save(w, session)
		})

		h.ServeHTTP(res, r.WithContext(ctx))
	})
}