// Uses cached-object to serve the request. If object is not cached it serves the request from the backend and also
// stores it in the cache for serving subsequent requests.
421023
func (c cacheObjects) GetObject(ctx context.Context, bucket, object string, startOffset int64, length int64, writer io.Writer, etag string, opts ObjectOptions) (err error) {
	GetObjectFn := c.GetObjectFn
	GetObjectInfoFn := c.GetObjectInfoFn

	if c.isCacheExclude(bucket, object) {
		return GetObjectFn(ctx, bucket, object, startOffset, length, writer, etag, opts)
	}
	// fetch cacheFSObjects if object is currently cached or nearest available cache drive
	dcache, err := c.cache.getCachedFSLoc(ctx, bucket, object)
	if err != nil {
		return GetObjectFn(ctx, bucket, object, startOffset, length, writer, etag, opts)
	}
	// stat object on backend
	objInfo, err := GetObjectInfoFn(ctx, bucket, object, opts)
	backendDown := backendDownError(err)
	if err != nil && !backendDown {
		if _, ok := err.(ObjectNotFound); ok {
			// Delete the cached entry if backend object was deleted.
			dcache.Delete(ctx, bucket, object)
		}
		return err
	}

	if !backendDown && !objInfo.IsCacheable() {
		return GetObjectFn(ctx, bucket, object, startOffset, length, writer, etag, opts)
	}

	if !backendDown && filterFromCache(objInfo.UserDefined) {
		return GetObjectFn(ctx, bucket, object, startOffset, length, writer, etag, opts)
	}

	cachedObjInfo, err := dcache.GetObjectInfo(ctx, bucket, object, opts)
	if err == nil {
		if backendDown {
			// If the backend is down, serve the request from cache.
			return dcache.Get(ctx, bucket, object, startOffset, length, writer, etag, opts)
		}
		if cachedObjInfo.ETag == objInfo.ETag && !isStaleCache(objInfo) {
			return dcache.Get(ctx, bucket, object, startOffset, length, writer, etag, opts)
		}
		dcache.Delete(ctx, bucket, object)
	}
	if startOffset != 0 || (length > 0 && length != objInfo.Size) {
		// We don't cache partial objects.
		return GetObjectFn(ctx, bucket, object, startOffset, length, writer, etag, opts)
	}
	if !dcache.diskAvailable(objInfo.Size) {
		return GetObjectFn(ctx, bucket, object, startOffset, length, writer, etag, opts)
	}
	// Initialize pipe.
	pipeReader, pipeWriter := io.Pipe()
	hashReader, err := hash.NewReader(pipeReader, objInfo.Size, "", "", objInfo.Size)
	if err != nil {
		return err
	}
	go func() {
		gerr := GetObjectFn(ctx, bucket, object, 0, objInfo.Size, io.MultiWriter(writer, pipeWriter), etag, opts)
		pipeWriter.CloseWithError(gerr) // Close writer explicitly signaling we wrote all data.
	}()

	opts.UserDefined = c.getMetadata(objInfo)
	err = dcache.Put(ctx, bucket, object, NewPutObjReader(hashReader, nil, nil), opts)
	if err != nil {
		return err
	}
	pipeReader.Close()
	return
}
49076
func Cached(d string) {
	if r, ok := relationalModelDefinition(false); ok {
		r.Cached = true
		dur, err := strconv.Atoi(d)
		if err != nil {
			dslengine.ReportError("Duration %s couldn't be parsed as integer", d)
		}
		r.CacheDuration = dur
	}
}
324404
func (h *modelRestHandler) ServeGet(w http.ResponseWriter, r *http.Request) error {
	if r.Method != "GET" {
		return errors.Trace(emitUnsupportedMethodErr(r.Method))
	}

	st, _, err := h.ctxt.stateForRequestAuthenticated(r)
	if err != nil {
		return errors.Trace(err)
	}
	defer st.Release()

	return errors.Trace(h.processGet(r, w, st.State))
}
218554
func NewCachedStorage(backend KeyPairStorage, cache KeyPairStorage) *CachedStorage {
	return &CachedStorage{
		cache:   cache,
		backend: backend,
	}
}
93820
func noCacheHandler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
		w.Header().Set("Pragma", "no-cache")
		w.Header().Set("Expires", "0")
		h.ServeHTTP(w, r)
	})
}
292373
func Cache(src, cache FS) FS {
	return &cachedFS{
		src:   src,
		cache: cache,
	}
}
1203859
func getCacheHandler(w http.ResponseWriter, r *http.Request) {
	target := r.URL.Path[len(cachePath):]
	if target == "" {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte("can't get a key if there is no key."))
		log.Print("empty request.")
		return
	}
	entry, err := cache.Get(target)
	if err != nil {
		errMsg := (err).Error()
		if strings.Contains(errMsg, "not found") {
			log.Print(err)
			w.WriteHeader(http.StatusNotFound)
			return
		}
		log.Print(err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(entry)
}
142311
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Request
	req := s.pool.request.Get().(*Request)
	reqHdr := s.pool.requestHeader.Get().(*Header)
	reqHdr.reset(r.Header)
	reqURL := s.pool.url.Get().(*URL)
	reqURL.reset(r.URL)
	req.reset(r, reqHdr, reqURL)
	req.config = s.config

	// Response
	res := s.pool.response.Get().(*Response)
	resHdr := s.pool.responseHeader.Get().(*Header)
	resHdr.reset(w.Header())
	res.reset(w, r, resHdr)
	res.config = s.config

	s.handler.ServeHTTP(req, res)

	s.pool.request.Put(req)
	s.pool.requestHeader.Put(reqHdr)
	s.pool.url.Put(reqURL)
	s.pool.response.Put(res)
	s.pool.responseHeader.Put(resHdr)
}
474760
func (h *Handler) ServeHTTPC(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
	stack := h.Pool.Get().(ContextHandler)
	stack.ServeHTTPC(ctx, rw, r)
	h.Pool.Put(stack)
}
556344
func (h *RestHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var err error
	switch r.Method {
	case "GET":
		err = errors.Annotate(h.GetHandler(w, r), "cannot retrieve model data")
	default:
		err = emitUnsupportedMethodErr(r.Method)
	}

	if err != nil {
		if err := sendJSONError(w, r, errors.Trace(err)); err != nil {
			logger.Errorf("%v", errors.Annotate(err, "cannot return error to user"))
		}
	}
}
361644
func (r *Route) serveMatchedRequest(rw http.ResponseWriter, req *http.Request, vars map[string]string) {
	globalVars.Lock()
	globalVars.v[req] = vars
	globalVars.Unlock()

	// Regardless if ServeHTTP panics (and potentially recovers) we can make sure to not leak
	// memory in globalVars for this request
	defer func() {
		globalVars.Lock()
		delete(globalVars.v, req)
		globalVars.Unlock()
	}()
	r.Handler.ServeHTTP(rw, req)
}
540832
func Backend(b backend.B, exp time.Duration) backend.B {
	return &caching.Backend{
		B: b,
		CacheGet: func(c context.Context, key caching.Key, l caching.Loader) (*caching.Value, error) {
			if key.Authority != backend.AsService {
				return l(c, key, nil)
			}

			// Is the item already cached?
			k := memcacheKey(&key)
			mci, err := mc.GetKey(c, k)
			switch err {
			case nil:
				// Value was cached, successfully retrieved.
				v, err := caching.DecodeValue(mci.Value())
				if err != nil {
					return nil, errors.Annotate(err, "failed to decode cache value from %q", k).Err()
				}
				return v, nil

			case mc.ErrCacheMiss:
				// Value was not cached. Load from Loader and cache.
				v, err := l(c, key, nil)
				if err != nil {
					return nil, err
				}

				// Attempt to cache the value. If this fails, we'll log a warning and
				// move on.
				err = func() error {
					d, err := v.Encode()
					if err != nil {
						return errors.Annotate(err, "failed to encode value").Err()
					}

					if len(d) > maxMemCacheSize {
						return errors.Reason("entry exceeds memcache size (%d > %d)", len(d), maxMemCacheSize).Err()
					}

					item := mc.NewItem(c, k).SetValue(d).SetExpiration(exp)
					if err := mc.Set(c, item); err != nil {
						return errors.Annotate(err, "").Err()
					}
					return nil
				}()
				if err != nil {
					log.Fields{
						log.ErrorKey: err,
						"key":        k,
					}.Warningf(c, "Failed to cache config.")
				}

				// Return the loaded value.
				return v, nil

			default:
				// Unknown memcache error.
				log.Fields{
					log.ErrorKey: err,
					"key":        k,
				}.Warningf(c, "Failed to decode memcached config.")
				return l(c, key, nil)
			}
		},
	}
}
292594
func Serve(h http.Handler) apex.Handler {
	if h == nil {
		h = http.DefaultServeMux
	}

	return &handler{h}
}
636582
func CachableResponseWriter(req *http.Request,
	statusCode int,
	resp http.ResponseWriter,
	opts Options) ([]cacheobject.Reason, time.Time, error) {
	return cacheobject.UsingRequestResponse(req, statusCode, resp.Header(), opts.PrivateCache)
}
521067
func (c *ObjectCache) Get(key string) (interface{}, error) {
	value, ok, err := c.cache.Get(objectEntry{key: key})
	if err != nil {
		return nil, err
	}
	if !ok {
		obj, err := c.updater()
		if err != nil {
			return nil, err
		}
		err = c.cache.Add(objectEntry{
			key: key,
			obj: obj,
		})
		if err != nil {
			return nil, err
		}
		return obj, nil
	}
	return value.(objectEntry).obj, nil
}
429409
func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) {
	cachedVal, ok := c.Get(cacheKey(req))
	if !ok {
		return
	}

	b := bytes.NewBuffer(cachedVal)
	return http.ReadResponse(bufio.NewReader(b), req)
}
791630
func (mw *Middleware) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if len(mw.Wares) < 1 {
		return
	}
	
	next := mw.Handler()

	//Finally, serve back up the chain
	next.ServeHTTP(w, req)
}