// ServeFile serves a file on a given route
187584
func (app *App) ServeFile(route, file string) *Router {
	return app.defaultRouter.ServeFile(route, file)
}
270613
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	// Clean path to canonical form and redirect.
	if p := cleanPath(req.URL.Path); p != req.URL.Path {
		w.Header().Set("Location", p)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}
	var match mux.RouteMatch
	var handler http.Handler
	if matched := r.Match(req, &match); matched {
		handler = match.Handler
		registerVars(req, match.Vars)
	}
	if handler == nil {
		if r.NotFoundHandler == nil {
			r.NotFoundHandler = http.NotFoundHandler()
		}
		handler = r.NotFoundHandler
	}
	if !r.KeepContext {
		defer context.Clear(req)
	}
	handler.ServeHTTP(w, req)
}
40290
func (bot *BotAPI) sendFile(config Fileable) (Message, error) {
	if config.useExistingFile() {
		return bot.sendExisting(config.method(), config)
	}

	return bot.uploadAndSend(config.method(), config)
}
836862
func (r *Response) serveFile(file string) error {
	log.Debugf("serving file %s", file)

	http.ServeFile(r.writer, r.request, file)
	return nil
}
55381
func File(path string) func(ctx *Context) {
	return func(ctx *Context) {
		ctx.ServeFile(path)
	}
}
146172
func (c *Controller) RenderFile(file *os.File, delivery ContentDisposition) Result {
	c.setStatusIfNil(http.StatusOK)

	var (
		modtime       = time.Now()
		fileInfo, err = file.Stat()
	)
	if err != nil {
		controllerLog.Error("RenderFile: error", "error", err)
	}
	if fileInfo != nil {
		modtime = fileInfo.ModTime()
	}
	return c.RenderBinary(file, filepath.Base(file.Name()), delivery, modtime)
}
313751
func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request, name string) (int, error) {

	location := name

	// Prevent absolute path access on Windows.
	// TODO remove when stdlib http.Dir fixes this.
	if runtime.GOOS == "windows" {
		if filepath.IsAbs(name[1:]) {
			return http.StatusNotFound, nil
		}
	}

	f, err := fs.Root.Open(name)
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// Likely the server is under load and ran out of file descriptors
		backoff := int(3 + rand.Int31()%3) // 3–5 seconds to prevent a stampede
		w.Header().Set("Retry-After", strconv.Itoa(backoff))
		return http.StatusServiceUnavailable, err
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// Return a different status code than above so as to distinguish these cases
		return http.StatusInternalServerError, err
	}

	// redirect to canonical path
	url := r.URL.Path
	if d.IsDir() {
		// Ensure / at end of directory url
		if !strings.HasSuffix(url, "/") {
			Redirect(w, r, path.Base(url)+"/", http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	} else {
		// Ensure no / at end of file url
		if strings.HasSuffix(url, "/") {
			Redirect(w, r, "../"+path.Base(url), http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	}

	// use contents of an index file, if present, for directory
	if d.IsDir() {
		for _, indexPage := range IndexPages {
			index := strings.TrimSuffix(name, "/") + "/" + indexPage
			ff, err := fs.Root.Open(index)
			if err != nil {
				continue
			}

			// this defer does not leak fds because previous iterations
			// of the loop must have had an err, so nothing to close
			defer ff.Close()

			dd, err := ff.Stat()
			if err != nil {
				ff.Close()
				continue
			}

			// Close previous file - release fd immediately
			f.Close()

			d = dd
			f = ff
			location = index
			break
		}
	}

	// Still a directory? (we didn't find an index file)
	// Return 404 to hide the fact that the folder exists
	if d.IsDir() {
		return http.StatusNotFound, nil
	}

	if fs.IsHidden(d) {
		return http.StatusNotFound, nil
	}

	filename := d.Name()

	for _, encoding := range staticEncodingPriority {
		if !strings.Contains(r.Header.Get("Accept-Encoding"), encoding) {
			continue
		}

		encodedFile, err := fs.Root.Open(location + staticEncoding[encoding])
		if err != nil {
			continue
		}

		encodedFileInfo, err := encodedFile.Stat()
		if err != nil {
			encodedFile.Close()
			continue
		}

		// Close previous file - release fd
		f.Close()

		// Stat is needed for generating valid ETag
		d = encodedFileInfo

		// Encoded file will be served
		f = encodedFile

		w.Header().Add("Vary", "Accept-Encoding")
		w.Header().Set("Content-Encoding", encoding)

		defer f.Close()
		break

	}

	// Experimental ETag header
	e := fmt.Sprintf(`W/"%x-%x"`, d.ModTime().Unix(), d.Size())
	w.Header().Set("ETag", e)

	// Note: Errors generated by ServeContent are written immediately
	// to the response. This usually only happens if seeking fails (rare).
	http.ServeContent(w, r, filename, d.ModTime(), f)

	return http.StatusOK, nil
}
1216194
func (s *Server) portFile(dirHint string) string {
	dirname := s.getOpts().PortsFileDir
	if dirHint != "" {
		dirname = dirHint
	}
	if dirname == _EMPTY_ {
		return _EMPTY_
	}
	return filepath.Join(dirname, fmt.Sprintf("%s_%d.ports", filepath.Base(os.Args[0]), os.Getpid()))
}
160115
func (c *DbClient) DeleteFile(path string) {
	c.Lock()
	defer c.Unlock()

	delete(c.db, path)
}
657622
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	for _, rule := range h.Rules {

		// First requirement: Base path must match and the path must be allowed.
		if !httpserver.Path(r.URL.Path).Matches(rule.Path) || !rule.AllowedPath(r.URL.Path) {
			continue
		}

		// In addition to matching the path, a request must meet some
		// other criteria before being proxied as FastCGI. For example,
		// we probably want to exclude static assets (CSS, JS, images...)
		// but we also want to be flexible for the script we proxy to.

		fpath := r.URL.Path

		if idx, ok := httpserver.IndexFile(h.FileSys, fpath, rule.IndexFiles); ok {
			fpath = idx
			// Index file present.
			// If request path cannot be split, return error.
			if !rule.canSplit(fpath) {
				return http.StatusInternalServerError, ErrIndexMissingSplit
			}
		} else {
			// No index file present.
			// If request path cannot be split, ignore request.
			if !rule.canSplit(fpath) {
				continue
			}
		}

		// These criteria work well in this order for PHP sites
		if !h.exists(fpath) || fpath[len(fpath)-1] == '/' || strings.HasSuffix(fpath, rule.Ext) {

			// Create environment for CGI script
			env, err := h.buildEnv(r, rule, fpath)
			if err != nil {
				return http.StatusInternalServerError, err
			}

			// Connect to FastCGI gateway
			fcgiBackend, err := rule.dialer.Dial()
			if err != nil {
				if err, ok := err.(net.Error); ok && err.Timeout() {
					return http.StatusGatewayTimeout, err
				}
				return http.StatusBadGateway, err
			}
			defer fcgiBackend.Close()
			fcgiBackend.SetReadTimeout(rule.ReadTimeout)
			fcgiBackend.SetSendTimeout(rule.SendTimeout)

			var resp *http.Response
			contentLength, _ := strconv.Atoi(r.Header.Get("Content-Length"))
			switch r.Method {
			case "HEAD":
				resp, err = fcgiBackend.Head(env)
			case "GET":
				resp, err = fcgiBackend.Get(env)
			case "OPTIONS":
				resp, err = fcgiBackend.Options(env)
			default:
				resp, err = fcgiBackend.Post(env, r.Method, r.Header.Get("Content-Type"), r.Body, contentLength)
			}

			if err != nil {
				if err, ok := err.(net.Error); ok && err.Timeout() {
					return http.StatusGatewayTimeout, err
				} else if err != io.EOF {
					return http.StatusBadGateway, err
				}
			}

			// Write response header
			writeHeader(w, resp)

			// Write the response body
			_, err = io.Copy(w, resp.Body)
			if err != nil {
				return http.StatusBadGateway, err
			}

			// Log any stderr output from upstream
			if stderr := fcgiBackend.StdErr(); stderr.Len() != 0 {
				// Remove trailing newline, error logger already does this.
				err = LogError(strings.TrimSuffix(stderr.String(), "\n"))
			}

			// Normally we would return the status code if it is an error status (>= 400),
			// however, upstream FastCGI apps don't know about our contract and have
			// probably already written an error page. So we just return 0, indicating
			// that the response body is already written. However, we do return any
			// error value so it can be logged.
			// Note that the proxy middleware works the same way, returning status=0.
			return 0, err
		}
	}

	return h.Next.ServeHTTP(w, r)
}
588173
func (c *Context) FormFile(key string) (*multipart.FileHeader, error) {
	_, fh, err := c.Request.FormFile(key)
	return fh, err
}
180438
func (l *Ledis) DumpFile(path string) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()

	return l.Dump(f)
}
183534
func serveSocketFile() {
	if SocketFile == nil || *SocketFile == "" {
		log.Infof("Not listening on socket file")
		return
	}
	name := *SocketFile

	// try to delete if file exists
	if _, err := os.Stat(name); err == nil {
		err = os.Remove(name)
		if err != nil {
			log.Exitf("Cannot remove socket file %v: %v", name, err)
		}
	}

	l, err := net.Listen("unix", name)
	if err != nil {
		log.Exitf("Error listening on socket file %v: %v", name, err)
	}
	log.Infof("Listening on socket file %v for gRPC", name)
	go GRPCServer.Serve(l)
}
1108377
func (client *storageRESTClient) AppendFile(volume, path string, buffer []byte) error {
	values := make(url.Values)
	values.Set(storageRESTVolume, volume)
	values.Set(storageRESTFilePath, path)
	reader := bytes.NewBuffer(buffer)
	respBody, err := client.call(storageRESTMethodAppendFile, values, reader, -1)
	defer http.DrainBody(respBody)
	return err
}
200743
func (s *SourceSpec) IgnoreFile(filename string) bool {
	if filename == "" {
		if _, ok := s.SourceFs.(*afero.OsFs); ok {
			return true
		}
		return false
	}

	base := filepath.Base(filename)

	if len(base) > 0 {
		first := base[0]
		last := base[len(base)-1]
		if first == '.' ||
			first == '#' ||
			last == '~' {
			return true
		}
	}

	if len(s.ignoreFilesRe) == 0 {
		return false
	}

	for _, re := range s.ignoreFilesRe {
		if re.MatchString(filename) {
			return true
		}
	}

	return false
}
223717
func (s *Subrouter) ServeStatic(rpath string, dir string) {
	fp := s.getFullPath(rpath)
	fs := http.Dir(dir)
	fh := http.StripPrefix(fp, http.FileServer(fs))
	root := path.Join(rpath, "/*filepath")
	// Add two more routes for handling index.html
	s.Handle("GET", rpath, fh)
	s.Handle("HEAD", rpath, fh)
	// and the files one...
	s.Handle("GET", root, fh)
	s.Handle("HEAD", root, fh)
}
779101
func (c *Client) OpenFile(path string, f int) (*File, error) {
	return c.open(path, flags(f))
}