// Cors defines middleware for setting and checking CORS headers,
432094
func Cors(opts ...*CorsOpts) fibre.MiddlewareFunc {
	return func(h fibre.HandlerFunc) fibre.HandlerFunc {
		return func(c *fibre.Context) error {

			var config *CorsOpts

			switch len(opts) {
			case 0:
				config = defaultCorsOpts
			default:
				config = opts[0]
			}

			// This is a socket
			if c.IsSocket() {
				return h(c)
			}

			// No origin is set
			if !c.IsOrigin() {
				return h(c)
			}

			// Origin not allowed
			if config.AllowedOrigin != "*" && config.AllowedOrigin != "=" && config.AllowedOrigin != c.Origin() {
				return h(c)
			}

			// Normalize AllowedMethods and make comma-separated-values
			normedMethods := []string{}
			for _, allowedMethod := range config.AllowedMethods {
				normed := http.CanonicalHeaderKey(allowedMethod)
				normedMethods = append(normedMethods, normed)
			}

			// Normalize AllowedHeaders and make comma-separated-values
			normedHeaders := []string{}
			for _, allowedHeader := range config.AllowedHeaders {
				normed := http.CanonicalHeaderKey(allowedHeader)
				normedHeaders = append(normedHeaders, normed)
			}

			if len(normedMethods) > 0 {
				c.Response().Header().Set(fibre.HeaderAccessControlAllowMethods, strings.Join(normedMethods, ","))
			}

			if len(normedHeaders) > 0 {
				c.Response().Header().Set(fibre.HeaderAccessControlAllowHeaders, strings.Join(normedHeaders, ","))
			}

			if config.AccessControlMaxAge > 0 {
				c.Response().Header().Set(fibre.HeaderAccessControlMaxAge, strconv.Itoa(config.AccessControlMaxAge))
			}

			switch config.AllowedOrigin {
			default:
				c.Response().Header().Set(fibre.HeaderAccessControlAllowOrigin, config.AllowedOrigin)
			case "=":
				c.Response().Header().Set(fibre.HeaderAccessControlAllowOrigin, c.Origin())
			case "*":
				c.Response().Header().Set(fibre.HeaderAccessControlAllowOrigin, "*")
			}

			if config.AccessControlAllowCredentials {
				c.Response().Header().Set(fibre.HeaderAccessControlAllowCredentials, "true")
			}

			return h(c)

		}
	}
}
864334
func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s := Server{Handler: h, Handshake: checkOrigin}
	s.serveWebSocket(w, req)
}
358003
func Methods(vals ...string) {
	if cors, ok := corsDefinition(); ok {
		cors.Methods = vals
	}
}
260513
func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
	headers := w.Header()
	origin := r.Header.Get("Origin")

	if r.Method != "OPTIONS" {
		c.logf("Preflight aborted: %s!=OPTIONS", r.Method)
		return
	}
	// Always set Vary headers
	// see https://github.com/rs/cors/issues/10,
	//     https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001
	headers.Add("Vary", "Origin")
	headers.Add("Vary", "Access-Control-Request-Method")
	headers.Add("Vary", "Access-Control-Request-Headers")

	if origin == "" {
		c.logf("Preflight aborted: empty origin")
		return
	}
	if !c.isOriginAllowed(r, origin) {
		c.logf("Preflight aborted: origin '%s' not allowed", origin)
		return
	}

	reqMethod := r.Header.Get("Access-Control-Request-Method")
	if !c.isMethodAllowed(reqMethod) {
		c.logf("Preflight aborted: method '%s' not allowed", reqMethod)
		return
	}
	reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers"))
	if !c.areHeadersAllowed(reqHeaders) {
		c.logf("Preflight aborted: headers '%v' not allowed", reqHeaders)
		return
	}
	headers.Set("Access-Control-Allow-Origin", origin)
	// Spec says: Since the list of methods can be unbounded, simply returning the method indicated
	// by Access-Control-Request-Method (if supported) can be enough
	headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod))
	if len(reqHeaders) > 0 {

		// Spec says: Since the list of headers can be unbounded, simply returning supported headers
		// from Access-Control-Request-Headers can be enough
		headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", "))
	}
	if c.allowCredentials {
		headers.Set("Access-Control-Allow-Credentials", "true")
	}
	if c.maxAge > 0 {
		headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge))
	}
	c.logf("Preflight response headers: %v", headers)
}
1196991
func DefaultCORSConfig() cors.Config {
	CORSConfig := cors.DefaultConfig()
	CORSConfig.AllowCredentials = true
	CORSConfig.AllowAllOrigins = true
	CORSConfig.AllowHeaders = []string{"*"}
	CORSConfig.AllowMethods = []string{"GET", "PUT", "POST", "DELETE", "OPTIONS"}
	return CORSConfig
}
337410
func (c *ReimportCall) Header() http.Header {
	if c.header_ == nil {
		c.header_ = make(http.Header)
	}
	return c.header_
}
377959
func (r *httpJSONResponse) Header(key string) string {
	return r.resp.Header.Get(key)
}
18685
func (app *App) CORSMiddleware(domains ...string) func(*Context) {
	return func(ctx *Context) {
		ctx.CORS(domains...)
	}
}
838765
func (c CORSMiddleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
		// If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
		// otherwise, all head values will be passed to HTTP handler
		corsHeaders := c.defaultHeaders
		if corsHeaders == "" {
			corsHeaders = "*"
		}

		logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
		w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
		w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
		w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
		return handler(ctx, w, r, vars)
	}
}
678113
func middleware(h http.Handler) http.Handler {
	if h == nil {
		return nil
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, cn := w.(http.CloseNotifier)
		_, fl := w.(http.Flusher)
		_, hj := w.(http.Hijacker)
		_, rf := w.(io.ReaderFrom)

		bw := basicWriter{ResponseWriter: w}

		if cn && fl && hj && rf {
			h.ServeHTTP(&fancyWriter{bw}, r)
		} else {
			h.ServeHTTP(&bw, r)
		}
		if !bw.headerWritten {
			bw.maybeClose()
		}
	})
}
726502
func Allow(opts *Options) http.HandlerFunc {
	// Allow default headers if nothing is specified.
	if len(opts.AllowHeaders) == 0 {
		opts.AllowHeaders = defaultAllowHeaders
	}

	for _, origin := range opts.AllowOrigins {
		pattern := regexp.QuoteMeta(origin)
		pattern = strings.Replace(pattern, "\\*", ".*", -1)
		pattern = strings.Replace(pattern, "\\?", ".", -1)
		allowOriginPatterns = append(allowOriginPatterns, "^"+pattern+"$")
	}

	return func(res http.ResponseWriter, req *http.Request) {
		var (
			origin           = req.Header.Get(headerOrigin)
			requestedMethod  = req.Header.Get(headerRequestMethod)
			requestedHeaders = req.Header.Get(headerRequestHeaders)
			// additional headers to be added
			// to the response.
			headers map[string]string
		)

		if req.Method == "OPTIONS" &&
			(requestedMethod != "" || requestedHeaders != "") {
			// TODO: if preflight, respond with exact headers if allowed
			headers = opts.PreflightHeader(origin, requestedMethod, requestedHeaders)
			for key, value := range headers {
				res.Header().Set(key, value)
			}
			res.WriteHeader(http.StatusOK)
			return
		}
		headers = opts.Header(origin)

		for key, value := range headers {
			res.Header().Set(key, value)
		}
	}
}
1350464
func CorsHandler(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		jsonp := false
		if cbName := req.FormValue("callback"); cbName != "" && req.Method == "GET" {
			rw.Header().Set("Content-Type", "text/javascript")
			rw.Write([]byte(fmt.Sprintf("%v(", cbName)))
			jsonp = true
		} else {
			rw.Header().Set("Content-Type", "application/json")
			if origin := req.Header.Get("Origin"); origin != "" {
				rw.Header().Add("Access-Control-Allow-Origin", origin)
			}
			if methods := req.Header.Get("Access-Control-Request-Method"); methods != "" {
				rw.Header().Add("Access-Control-Allow-Methods", methods)
			}
			if headers := req.Header.Get("Access-Control-Request-Headers"); headers != "" {
				rw.Header().Add("Access-Control-Allow-Headers", headers)
			}
			rw.Header().Add("Access-Control-Allow-Credentials", "true")

			// If we're getting an OPTIONS request, just send response
			if req.Method == "OPTIONS" {
				rw.WriteHeader(http.StatusOK)
				return
			}
		}
		handler.ServeHTTP(rw, req)
		if jsonp {
			rw.Write([]byte(");"))
		}
	})
}
249930
func (c *AdminCreateUserCall) Header() http.Header {
	if c.header_ == nil {
		c.header_ = make(http.Header)
	}
	return c.header_
}
146822
func (b *SystemBackend) handleCORSRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	corsConf := b.Core.corsConfig

	enabled := corsConf.IsEnabled()

	resp := &logical.Response{
		Data: map[string]interface{}{
			"enabled": enabled,
		},
	}

	if enabled {
		corsConf.RLock()
		resp.Data["allowed_origins"] = corsConf.AllowedOrigins
		resp.Data["allowed_headers"] = corsConf.AllowedHeaders
		corsConf.RUnlock()
	}

	return resp, nil
}
174492
func (r *Request) Header(key, value string) *Request {
	r.req.Header.Set(key, value)
	return r
}
989756
func (r *Response) Headers() *Object {
	var value map[string]interface{}
	if !r.chain.failed() {
		value, _ = canonMap(&r.chain, r.resp.Header)
	}
	return &Object{r.chain, value}
}
32705
func (s *State) Middleware(c *router.Context, next router.Handler) {
	state, settings := s.checkSettings(c.Context)
	if settings.Enabled {
		started := clock.Now(c.Context)
		req := c.Request
		userAgent, ok := req.Header["User-Agent"]
		if !ok || len(userAgent) == 0 {
			userAgent = []string{"Unknown"}
		}
		ctx := c.Context
		contentLength := c.Request.ContentLength
		nrw := newResponseWriter(c.Writer)
		c.Writer = nrw
		defer func() {
			dur := clock.Now(ctx).Sub(started)
			metric.UpdateServerMetrics(ctx, c.HandlerPath, nrw.Status(), dur,
				contentLength, nrw.Size(), userAgent[0])
		}()
		next(c)
		s.flushIfNeeded(ctx, req, state, settings)
	} else {
		next(c)
	}
}