// ServeFiles exposes the httprouter ServeFiles method.
// NOTE: does not handle errors nor panics.
972184
func (r *Router) ServeFiles(path string, root http.FileSystem) {
	r.Router.ServeFiles(path, root)
}
950979
func ProcessPostedFiles(r *http.Request, sfHandler SingleFileHandler) error {

	// parse multipart data
	err := r.ParseMultipartForm(100000)
	if err != nil {
		return err
	}

	// open files
	files := r.MultipartForm.File["file"]
	log.Println("ProcessPostedFiles: got " + strconv.Itoa(len(files)) + " files")
	for i, _ := range files {
		if result, err := sfHandler(files[i]); !result {
			if err != nil {
				return err
			}
			return errors.New("Operation canceled")
		}
	}
	log.Println("ProcessPostedFiles: finished")
	return nil
}
111197
func (r *SubRouter) ServeFile(route, file string) *SubRouter {
	route = r.prefixedRoute(route)
	r.parent.handleReg(MethodGET, route, func(ctx *Context) {
		ctx.SendFile(file)
	}, r.prefixes)

	return r
}
1028546
func serveLists(resp http.ResponseWriter, req *http.Request, conf *safebrowsing.Config) {
	var mime string
	switch req.URL.Query().Get("alt") {
	case "", "json":
		mime = mimeJSON
	case "proto":
		mime = mimeProto
	default:
		http.Error(resp, "invalid request type", http.StatusBadRequest)
		return
	}
	if req.Method != "GET" {
		http.Error(resp, "invalid method", http.StatusBadRequest)
		return
	}

	tls := safebrowsing.DefaultThreatLists
	if len(conf.ThreatLists) != 0 {
		tls = conf.ThreatLists
	}

	pbResp := new(pb.ListThreatListsResponse)
	for _, td := range tls {
		pbResp.ThreatLists = append(pbResp.ThreatLists, &pb.ThreatListDescriptor{
			ThreatType:      pb.ThreatType(td.ThreatType),
			PlatformType:    pb.PlatformType(td.PlatformType),
			ThreatEntryType: pb.ThreatEntryType(td.ThreatEntryType),
		})
	}

	// Encode the response message.
	if err := marshal(resp, pbResp, mime); err != nil {
		http.Error(resp, err.Error(), http.StatusInternalServerError)
		return
	}
}
836862
func (r *Response) serveFile(file string) error {
	log.Debugf("serving file %s", file)

	http.ServeFile(r.writer, r.request, file)
	return nil
}
185748
func (h errorHandler) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	defer h.recovery(ctx, w, r)

	rcode, err := plugin.NextOrFailure(h.Name(), h.Next, ctx, w, r)

	if err != nil {
		state := request.Request{W: w, Req: r}
		errMsg := fmt.Sprintf("%s [ERROR %d %s %s] %v", time.Now().Format(timeFormat), rcode, state.Name(), state.Type(), err)

		h.Log.Println(errMsg)
	}

	return rcode, err
}
8398
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s.router.ServeHTTP(w, req)
}
1186170
func (v *GenerateServiceResponse) GetFiles() (o map[string][]byte) {
	if v != nil && v.Files != nil {
		return v.Files
	}

	return
}
201435
func (ctrl *Controller) ServeFiles(path, filename string) error {
	if strings.Contains(path, ":") {
		return fmt.Errorf("path may only include wildcards that match the entire end of the URL (e.g. *filepath)")
	}
	LogInfo(ctrl.Context, "mount file", "name", filename, "route", fmt.Sprintf("GET %s", path))
	handler := func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		if !ContextResponse(ctx).Written() {
			return ctrl.FileHandler(path, filename)(ctx, rw, req)
		}
		return nil
	}
	ctrl.Service.Mux.Handle("GET", path, ctrl.MuxHandler("serve", handler, nil))
	return nil
}
547122
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	for _, rule := range h.Rules {
		// First requirement: Base path must match request path. If it doesn't,
		// we check to make sure the leading slash is not missing, and if so,
		// we check again with it prepended. This is in case people forget
		// a leading slash when performing rewrites, and we don't want to expose
		// the contents of the (likely PHP) script. See issue #1645.
		hpath := httpserver.Path(r.URL.Path)
		if !hpath.Matches(rule.Path) {
			if strings.HasPrefix(string(hpath), "/") {
				// this is a normal-looking path, and it doesn't match; try next rule
				continue
			}
			hpath = httpserver.Path("/" + string(hpath)) // prepend leading slash
			if !hpath.Matches(rule.Path) {
				// even after fixing the request path, it still doesn't match; try next rule
				continue
			}
		}
		// The path must also be allowed (not ignored).
		if !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
			address, err := rule.Address()
			if err != nil {
				return http.StatusBadGateway, err
			}
			network, address := parseAddress(address)

			ctx := context.Background()
			if rule.ConnectTimeout > 0 {
				var cancel context.CancelFunc
				ctx, cancel = context.WithTimeout(ctx, rule.ConnectTimeout)
				defer cancel()
			}

			fcgiBackend, err := DialContext(ctx, network, address)
			if err != nil {
				return http.StatusBadGateway, err
			}
			defer fcgiBackend.Close()

			// read/write timeouts
			if err := fcgiBackend.SetReadTimeout(rule.ReadTimeout); err != nil {
				return http.StatusInternalServerError, err
			}
			if err := fcgiBackend.SetSendTimeout(rule.SendTimeout); err != nil {
				return http.StatusInternalServerError, err
			}

			var resp *http.Response

			var contentLength int64
			// if ContentLength is already set
			if r.ContentLength > 0 {
				contentLength = r.ContentLength
			} else {
				contentLength, _ = strconv.ParseInt(r.Header.Get("Content-Length"), 10, 64)
			}
			switch r.Method {
			case "HEAD":
				resp, err = fcgiBackend.Head(env)
			case "GET":
				resp, err = fcgiBackend.Get(env, r.Body, contentLength)
			case "OPTIONS":
				resp, err = fcgiBackend.Options(env)
			default:
				resp, err = fcgiBackend.Post(env, r.Method, r.Header.Get("Content-Type"), r.Body, contentLength)
			}

			if resp != nil && resp.Body != nil {
				defer resp.Body.Close()
			}

			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 fcgiBackend.stderr.Len() != 0 {
				// Remove trailing newline, error logger already does this.
				err = LogError(strings.TrimSuffix(fcgiBackend.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)
}
1114742
func (r *Router) ServeFile(route, file string) *Router {
	r.Handle(MethodGET, route, func(ctx *Context) {
		ctx.SendFile(file)
	})
	return r
}
1305328
func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	c := r.pool.Get().(*Context)
	c.init(res, req)
	if r.UseEscapedPath {
		c.handlers, c.pnames = r.find(req.Method, r.normalizeRequestPath(req.URL.EscapedPath()), c.pvalues)
		for i, v := range c.pvalues {
			c.pvalues[i], _ = url.QueryUnescape(v)
		}
	} else {
		c.handlers, c.pnames = r.find(req.Method, r.normalizeRequestPath(req.URL.Path), c.pvalues)
	}
	if err := c.Next(); err != nil {
		r.handleError(c, err)
	}
	r.pool.Put(c)
}
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
}
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)
}
1188072
func (mr *MountableRouter) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	mr.Delegate.ServeHTTP(rw, r)
}
611081
func LoadFiles(root string, ignoreFile []byte) (files []string, err error) {
	err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		mode := info.Mode()
		if !(mode.IsDir() || mode.IsRegular() || mode&os.ModeSymlink == os.ModeSymlink) {
			return nil
		}

		rel, err := filepath.Rel(root, path)
		if err != nil {
			return err
		}

		matched, err := gitignorer.GitIgnore(bytes.NewReader(ignoreFile), rel)
		if err != nil {
			return err
		}

		if mode.IsDir() && matched {
			return filepath.SkipDir
		} else if mode.IsDir() || matched {
			return nil
		}

		files = append(files, rel)

		return nil
	})

	return
}
13495
func FileServer(dir http.Dir) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		p := path.Join(string(dir), r.URL.Path)
		if f, err := os.Stat(p); err == nil && !f.IsDir() {
			http.ServeFile(w, r, p)
			return
		}

		http.NotFound(w, r)
	})
}