//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Request Middleware(s)
//___________________________________
423751
func parseRequestURL(c *Client, r *Request) error {
	// GitHub #103 Path Params
	if len(r.pathParams) > 0 {
		for p, v := range r.pathParams {
			r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1)
		}
	}
	if len(c.pathParams) > 0 {
		for p, v := range c.pathParams {
			r.URL = strings.Replace(r.URL, "{"+p+"}", url.PathEscape(v), -1)
		}
	}

	// Parsing request URL
	reqURL, err := url.Parse(r.URL)
	if err != nil {
		return err
	}

	// If Request.URL is relative path then added c.HostURL into
	// the request URL otherwise Request.URL will be used as-is
	if !reqURL.IsAbs() {
		r.URL = reqURL.String()
		if len(r.URL) > 0 && r.URL[0] != '/' {
			r.URL = "/" + r.URL
		}

		reqURL, err = url.Parse(c.HostURL + r.URL)
		if err != nil {
			return err
		}
	}

	// Adding Query Param
	query := make(url.Values)
	for k, v := range c.QueryParam {
		for _, iv := range v {
			query.Add(k, iv)
		}
	}

	for k, v := range r.QueryParam {
		// remove query param from client level by key
		// since overrides happens for that key in the request
		query.Del(k)

		for _, iv := range v {
			query.Add(k, iv)
		}
	}

	// GitHub #123 Preserve query string order partially.
	// Since not feasible in `SetQuery*` resty methods, because
	// standard package `url.Encode(...)` sorts the query params
	// alphabetically
	if len(query) > 0 {
		if IsStringEmpty(reqURL.RawQuery) {
			reqURL.RawQuery = query.Encode()
		} else {
			reqURL.RawQuery = reqURL.RawQuery + "&" + query.Encode()
		}
	}

	r.URL = reqURL.String()

	return nil
}
1280808
func Middleware(c *router.Context, next router.Handler) {
	if tok := c.Request.Header.Get(Header); tok != "" {
		// TODO(smut): Support requests to other modules, versions.
		aud := "https://" + info.DefaultVersionHostname(c.Context)
		logging.Debugf(c.Context, "expecting VM token for: %s", aud)
		switch p, err := Verify(c.Context, tok); {
		case transient.Tag.In(err):
			logging.WithError(err).Errorf(c.Context, "transient error verifying VM token")
			http.Error(c.Writer, "error: failed to verify VM token", http.StatusInternalServerError)
			return
		case err != nil:
			logging.WithError(err).Errorf(c.Context, "invalid VM token")
			http.Error(c.Writer, "error: invalid VM token", http.StatusUnauthorized)
			return
		case p.Audience != aud:
			logging.Errorf(c.Context, "received VM token intended for: %s", p.Audience)
			http.Error(c.Writer, "error: VM token audience mismatch", http.StatusUnauthorized)
			return
		default:
			logging.Debugf(c.Context, "received VM token from %q in %q in %q for: %s", p.Instance, p.Zone, p.Project, p.Audience)
			c.Context = withPayload(c.Context, p)
		}
	}
	next(c)
}
830838
func Middleware(level int, o ...Option) goa.Middleware {
	opts := options{
		ignoreRange:  true,
		minSize:      256,
		contentTypes: defaultContentTypes,
	}
	opts.statusCodes = make(map[int]struct{}, len(defaultStatusCodes))
	for _, v := range defaultStatusCodes {
		opts.statusCodes[v] = struct{}{}
	}
	for _, opt := range o {
		err := opt(&opts)
		if err != nil {
			panic(err)
		}
	}
	gzipPool := sync.Pool{
		New: func() interface{} {
			gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
			if err != nil {
				panic(err)
			}
			return gz
		},
	}
	return func(h goa.Handler) goa.Handler {
		return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) (err error) {
			// Skip compression if the client doesn't accept gzip encoding, is
			// requesting a WebSocket or the data is already compressed.
			if !strings.Contains(req.Header.Get(headerAcceptEncoding), encodingGzip) ||
				len(req.Header.Get(headerSecWebSocketKey)) > 0 ||
				rw.Header().Get(headerContentEncoding) == encodingGzip ||
				(!opts.ignoreRange && req.Header.Get(headerRange) != "") {
				return h(ctx, rw, req)
			}

			// Set the appropriate gzip headers.
			resp := goa.ContextResponse(ctx)

			// Get the original http.ResponseWriter
			w := resp.SwitchWriter(nil)

			// Wrap the original http.ResponseWriter with our gzipResponseWriter
			grw := &gzipResponseWriter{
				ResponseWriter: w,
				pool:           &gzipPool,
				statusCode:     http.StatusOK,
				o:              opts,
			}

			// Set the new http.ResponseWriter
			resp.SwitchWriter(grw)

			// We cannot do ranges, if possibly gzipped responses.
			req.Header.Del("Range")

			// Call the next handler supplying the gzipResponseWriter instead of
			// the original.
			err = h(ctx, rw, req)
			if err != nil {
				return
			}

			// Check for uncompressed data
			if grw.buf.Len() > 0 {
				w.Header().Set(headerContentLength, strconv.Itoa(grw.buf.Len()))
				w.WriteHeader(grw.statusCode)
				_, err = w.Write(grw.buf.Bytes())
				return
			}

			// Flush compressor.
			if grw.gzw != nil {
				if err = grw.gzw.Close(); err != nil {
					return
				}
				gzipPool.Put(grw.gzw)
				return
			}
			// No writes, set status code.
			if grw.shouldCompress == nil {
				w.WriteHeader(grw.statusCode)
			}
			return
		}
	}
}
1274810
func HandleMiddlewares(h http.Handler, adapters ...Middleware) http.Handler {
	// To make the middleware run in the order in which they are specified,
	// we reverse through them in the Middleware function, rather than just
	// ranging over them
	for i := len(adapters) - 1; i >= 0; i-- {
		h = adapters[i](h)
	}
	return h
}
283073
func Middleware(options Options) gin.HandlerFunc {
	if options.AllowHeaders == nil {
		options.AllowHeaders = defaultAllowHeaders
	}

	if options.AllowMethods == nil {
		options.AllowMethods = defaultAllowMethods
	}

	return func(c *gin.Context) {
		req := c.Request
		res := c.Writer
		origin := req.Header.Get("Origin")
		requestMethod := req.Header.Get("Access-Control-Request-Method")
		requestHeaders := req.Header.Get("Access-Control-Request-Headers")

		if len(options.AllowOrigins) > 0 {
			res.Header().Set("Access-Control-Allow-Origin", strings.Join(options.AllowOrigins, " "))
		} else {
			res.Header().Set("Access-Control-Allow-Origin", origin)
		}

		if options.AllowCredentials {
			res.Header().Set("Access-Control-Allow-Credentials", "true")
		}

		if len(options.ExposeHeaders) > 0 {
			res.Header().Set("Access-Control-Expose-Headers", strings.Join(options.ExposeHeaders, ","))
		}

		if req.Method == "OPTIONS" {
			if len(options.AllowMethods) > 0 {
				res.Header().Set("Access-Control-Allow-Methods", strings.Join(options.AllowMethods, ","))
			} else if requestMethod != "" {
				res.Header().Set("Access-Control-Allow-Methods", requestMethod)
			}

			if len(options.AllowHeaders) > 0 {
				res.Header().Set("Access-Control-Allow-Headers", strings.Join(options.AllowHeaders, ","))
			} else if requestHeaders != "" {
				res.Header().Set("Access-Control-Allow-Headers", requestHeaders)
			}

			if options.MaxAge > time.Duration(0) {
				res.Header().Set("Access-Control-Max-Age", strconv.FormatInt(int64(options.MaxAge/time.Second), 10))
			}

			c.AbortWithStatus(http.StatusOK)
		} else {
			c.Next()
		}
	}
}
1288261
func Middleware(store sessions.Store) echo.MiddlewareFunc {
	c := DefaultConfig
	c.Store = store
	return MiddlewareWithConfig(c)
}
1036767
func main() {
	app := gear.New()

	// Add logging middleware
	app.UseHandler(logging.Default(true))

	// Add router middleware
	router := gear.NewRouter()

	// try: http://127.0.0.1:3000/hello
	router.Get("/hello", func(ctx *gear.Context) error {
		return ctx.HTML(200, "<h1>Hello, Gear!</h1>")
	})

	// try: http://127.0.0.1:3000/test?query=hello
	router.Otherwise(func(ctx *gear.Context) error {
		return ctx.JSON(200, map[string]interface{}{
			"Host":    ctx.Host,
			"Method":  ctx.Method,
			"Path":    ctx.Path,
			"URL":     ctx.Req.URL.String(),
			"Headers": ctx.Req.Header,
		})
	})
	app.UseHandler(router)
	app.Error(app.Listen(":3000"))
}
1154541
func (s *ServeMux) Middleware(path string, middleware Middleware) {
	s.Route(path).Middleware(middleware)
}
561202
func Req(verb string, url string, ro *RequestOptions) (*Response, error) {
	return DoRegularRequest(verb, url, ro)
}
556236
func (m MiddleFn) ServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request, next Handler) context.Context {
	return m(ctx, w, r, next)
}
673767
func (c Client) Request(method string, path string, body []byte) (*http.Response, error) {
	url := c.ControllerURL

	if strings.Contains(path, "?") {
		parts := strings.Split(path, "?")
		url.Path = parts[0]
		url.RawQuery = parts[1]
	} else {
		url.Path = path
	}

	req, err := http.NewRequest(method, url.String(), bytes.NewBuffer(body))

	if err != nil {
		return nil, err
	}

	req.Header.Add("Content-Type", "application/json")

	if c.Token != "" {
		req.Header.Add("Authorization", "token "+c.Token)
	}

	addUserAgent(&req.Header)

	res, err := c.HTTPClient.Do(req)

	if err != nil {
		return nil, err
	}

	if err = checkForErrors(res, ""); err != nil {
		return nil, err
	}

	checkAPICompatibility(res.Header.Get("DEIS_API_VERSION"))

	return res, nil
}
767564
func (r *TaskService) Request(taskId string) *TaskRequestCall {
	c := &TaskRequestCall{s: r.s, urlParams_: make(gensupport.URLParams)}
	c.taskId = taskId
	return c
}
164225
func Middleware(h http.Handler, r *Resolver) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ip := r.RealIP(req)
		h.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), realIPKey, ip)))
	})
}
750556
func (r *Request) Params(params map[string]string) *Request {
	r.Use(url.Params(params))
	return r
}
289140
func (flcliapi *Flcliapi) Request(request []string) (reply []string, err error) {
	flcliapi.pipe.SendMessage("REQUEST", request)
	reply, err = flcliapi.pipe.RecvMessage(0)
	if err == nil {
		status := reply[0]
		reply = reply[1:]
		if status == "FAILED" {
			reply = reply[0:0]
		}
	}
	return
}
1040018
func (r *route) Middlewares(
	middlewares ...types.Middleware) types.Route {
	r.middlewares = append(r.middlewares, middlewares...)
	return r
}
32598
func NewRequest() *Request {
	ctx := context.New()
	ctx.Client.Transport = DefaultTransport
	ctx.Request.Header.Set("User-Agent", UserAgent)
	return &Request{
		Context:    ctx,
		Middleware: middleware.New(),
	}
}