1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // HTTP file system request handler
12 "internal/safefilepath"
28 // A Dir implements FileSystem using the native file system restricted to a
29 // specific directory tree.
31 // While the FileSystem.Open method takes '/'-separated paths, a Dir's string
32 // value is a filename on the native file system, not a URL, so it is separated
33 // by filepath.Separator, which isn't necessarily '/'.
35 // Note that Dir could expose sensitive files and directories. Dir will follow
36 // symlinks pointing out of the directory tree, which can be especially dangerous
37 // if serving from a directory in which users are able to create arbitrary symlinks.
38 // Dir will also allow access to files and directories starting with a period,
39 // which could expose sensitive directories like .git or sensitive files like
40 // .htpasswd. To exclude files with a leading period, remove the files/directories
41 // from the server or create a custom FileSystem implementation.
43 // An empty Dir is treated as ".".
46 // mapOpenError maps the provided non-nil error from opening name
47 // to a possibly better non-nil error. In particular, it turns OS-specific errors
48 // about opening files in non-directories into fs.ErrNotExist. See Issues 18984 and 49552.
49 func mapOpenError(originalErr error, name string, sep rune, stat func(string) (fs.FileInfo, error)) error {
50 if errors.Is(originalErr, fs.ErrNotExist) || errors.Is(originalErr, fs.ErrPermission) {
54 parts := strings.Split(name, string(sep))
55 for i := range parts {
59 fi, err := stat(strings.Join(parts[:i+1], string(sep)))
70 // Open implements FileSystem using os.Open, opening files for reading rooted
71 // and relative to the directory d.
72 func (d Dir) Open(name string) (File, error) {
73 path, err := safefilepath.FromFS(path.Clean("/" + name))
75 return nil, errors.New("http: invalid or unsafe file path")
81 fullName := filepath.Join(dir, path)
82 f, err := os.Open(fullName)
84 return nil, mapOpenError(err, fullName, filepath.Separator, os.Stat)
89 // A FileSystem implements access to a collection of named files.
90 // The elements in a file path are separated by slash ('/', U+002F)
91 // characters, regardless of host operating system convention.
92 // See the FileServer function to convert a FileSystem to a Handler.
94 // This interface predates the fs.FS interface, which can be used instead:
95 // the FS adapter function converts an fs.FS to a FileSystem.
96 type FileSystem interface {
97 Open(name string) (File, error)
100 // A File is returned by a FileSystem's Open method and can be
101 // served by the FileServer implementation.
103 // The methods should behave the same as those on an *os.File.
104 type File interface {
108 Readdir(count int) ([]fs.FileInfo, error)
109 Stat() (fs.FileInfo, error)
112 type anyDirs interface {
118 type fileInfoDirs []fs.FileInfo
120 func (d fileInfoDirs) len() int { return len(d) }
121 func (d fileInfoDirs) isDir(i int) bool { return d[i].IsDir() }
122 func (d fileInfoDirs) name(i int) string { return d[i].Name() }
124 type dirEntryDirs []fs.DirEntry
126 func (d dirEntryDirs) len() int { return len(d) }
127 func (d dirEntryDirs) isDir(i int) bool { return d[i].IsDir() }
128 func (d dirEntryDirs) name(i int) string { return d[i].Name() }
130 func dirList(w ResponseWriter, r *Request, f File) {
131 // Prefer to use ReadDir instead of Readdir,
132 // because the former doesn't require calling
133 // Stat on every entry of a directory on Unix.
136 if d, ok := f.(fs.ReadDirFile); ok {
137 var list dirEntryDirs
138 list, err = d.ReadDir(-1)
141 var list fileInfoDirs
142 list, err = f.Readdir(-1)
147 logf(r, "http: error reading directory: %v", err)
148 Error(w, "Error reading directory", StatusInternalServerError)
151 sort.Slice(dirs, func(i, j int) bool { return dirs.name(i) < dirs.name(j) })
153 w.Header().Set("Content-Type", "text/html; charset=utf-8")
154 fmt.Fprintf(w, "<pre>\n")
155 for i, n := 0, dirs.len(); i < n; i++ {
160 // name may contain '?' or '#', which must be escaped to remain
161 // part of the URL path, and not indicate the start of a query
162 // string or fragment.
163 url := url.URL{Path: name}
164 fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
166 fmt.Fprintf(w, "</pre>\n")
169 // ServeContent replies to the request using the content in the
170 // provided ReadSeeker. The main benefit of ServeContent over io.Copy
171 // is that it handles Range requests properly, sets the MIME type, and
172 // handles If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since,
173 // and If-Range requests.
175 // If the response's Content-Type header is not set, ServeContent
176 // first tries to deduce the type from name's file extension and,
177 // if that fails, falls back to reading the first block of the content
178 // and passing it to DetectContentType.
179 // The name is otherwise unused; in particular it can be empty and is
180 // never sent in the response.
182 // If modtime is not the zero time or Unix epoch, ServeContent
183 // includes it in a Last-Modified header in the response. If the
184 // request includes an If-Modified-Since header, ServeContent uses
185 // modtime to decide whether the content needs to be sent at all.
187 // The content's Seek method must work: ServeContent uses
188 // a seek to the end of the content to determine its size.
190 // If the caller has set w's ETag header formatted per RFC 7232, section 2.3,
191 // ServeContent uses it to handle requests using If-Match, If-None-Match, or If-Range.
193 // Note that *os.File implements the io.ReadSeeker interface.
194 func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker) {
195 sizeFunc := func() (int64, error) {
196 size, err := content.Seek(0, io.SeekEnd)
200 _, err = content.Seek(0, io.SeekStart)
206 serveContent(w, req, name, modtime, sizeFunc, content)
209 // errSeeker is returned by ServeContent's sizeFunc when the content
210 // doesn't seek properly. The underlying Seeker's error text isn't
211 // included in the sizeFunc reply so it's not sent over HTTP to end
213 var errSeeker = errors.New("seeker can't seek")
215 // errNoOverlap is returned by serveContent's parseRange if first-byte-pos of
216 // all of the byte-range-spec values is greater than the content size.
217 var errNoOverlap = errors.New("invalid range: failed to overlap")
219 // if name is empty, filename is unknown. (used for mime type, before sniffing)
220 // if modtime.IsZero(), modtime is unknown.
221 // content must be seeked to the beginning of the file.
222 // The sizeFunc is called at most once. Its error, if any, is sent in the HTTP response.
223 func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time, sizeFunc func() (int64, error), content io.ReadSeeker) {
224 setLastModified(w, modtime)
225 done, rangeReq := checkPreconditions(w, r, modtime)
232 // If Content-Type isn't set, use the file's extension to find it, but
233 // if the Content-Type is unset explicitly, do not sniff the type.
234 ctypes, haveType := w.Header()["Content-Type"]
237 ctype = mime.TypeByExtension(filepath.Ext(name))
239 // read a chunk to decide between utf-8 text and binary
240 var buf [sniffLen]byte
241 n, _ := io.ReadFull(content, buf[:])
242 ctype = DetectContentType(buf[:n])
243 _, err := content.Seek(0, io.SeekStart) // rewind to output whole file
245 Error(w, "seeker can't seek", StatusInternalServerError)
249 w.Header().Set("Content-Type", ctype)
250 } else if len(ctypes) > 0 {
254 size, err := sizeFunc()
256 Error(w, err.Error(), StatusInternalServerError)
260 // Should never happen but just to be sure
261 Error(w, "negative content size computed", StatusInternalServerError)
265 // handle Content-Range header.
267 var sendContent io.Reader = content
268 ranges, err := parseRange(rangeReq, size)
273 // Some clients add a Range header to all requests to
274 // limit the size of the response. If the file is empty,
275 // ignore the range header and respond with a 200 rather
280 w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
283 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
287 if sumRangesSize(ranges) > size {
288 // The total number of bytes in all the ranges
289 // is larger than the size of the file by
290 // itself, so this is probably an attack, or a
291 // dumb client. Ignore the range request.
295 case len(ranges) == 1:
296 // RFC 7233, Section 4.1:
297 // "If a single part is being transferred, the server
298 // generating the 206 response MUST generate a
299 // Content-Range header field, describing what range
300 // of the selected representation is enclosed, and a
301 // payload consisting of the range.
303 // A server MUST NOT generate a multipart response to
304 // a request for a single range, since a client that
305 // does not request multiple parts might not support
306 // multipart responses."
308 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
309 Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
313 code = StatusPartialContent
314 w.Header().Set("Content-Range", ra.contentRange(size))
315 case len(ranges) > 1:
316 sendSize = rangesMIMESize(ranges, ctype, size)
317 code = StatusPartialContent
320 mw := multipart.NewWriter(pw)
321 w.Header().Set("Content-Type", "multipart/byteranges; boundary="+mw.Boundary())
323 defer pr.Close() // cause writing goroutine to fail and exit if CopyN doesn't finish.
325 for _, ra := range ranges {
326 part, err := mw.CreatePart(ra.mimeHeader(ctype, size))
328 pw.CloseWithError(err)
331 if _, err := content.Seek(ra.start, io.SeekStart); err != nil {
332 pw.CloseWithError(err)
335 if _, err := io.CopyN(part, content, ra.length); err != nil {
336 pw.CloseWithError(err)
345 w.Header().Set("Accept-Ranges", "bytes")
346 if w.Header().Get("Content-Encoding") == "" {
347 w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
352 if r.Method != "HEAD" {
353 io.CopyN(w, sendContent, sendSize)
357 // scanETag determines if a syntactically valid ETag is present at s. If so,
358 // the ETag and remaining text after consuming ETag is returned. Otherwise,
359 // it returns "", "".
360 func scanETag(s string) (etag string, remain string) {
361 s = textproto.TrimString(s)
363 if strings.HasPrefix(s, "W/") {
366 if len(s[start:]) < 2 || s[start] != '"' {
369 // ETag is either W/"text" or "text".
371 for i := start + 1; i < len(s); i++ {
374 // Character values allowed in ETags.
375 case c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:
377 return s[:i+1], s[i+1:]
385 // etagStrongMatch reports whether a and b match using strong ETag comparison.
386 // Assumes a and b are valid ETags.
387 func etagStrongMatch(a, b string) bool {
388 return a == b && a != "" && a[0] == '"'
391 // etagWeakMatch reports whether a and b match using weak ETag comparison.
392 // Assumes a and b are valid ETags.
393 func etagWeakMatch(a, b string) bool {
394 return strings.TrimPrefix(a, "W/") == strings.TrimPrefix(b, "W/")
397 // condResult is the result of an HTTP request precondition check.
398 // See https://tools.ietf.org/html/rfc7232 section 3.
402 condNone condResult = iota
407 func checkIfMatch(w ResponseWriter, r *Request) condResult {
408 im := r.Header.Get("If-Match")
413 im = textproto.TrimString(im)
424 etag, remain := scanETag(im)
428 if etagStrongMatch(etag, w.Header().get("Etag")) {
437 func checkIfUnmodifiedSince(r *Request, modtime time.Time) condResult {
438 ius := r.Header.Get("If-Unmodified-Since")
439 if ius == "" || isZeroTime(modtime) {
442 t, err := ParseTime(ius)
447 // The Last-Modified header truncates sub-second precision so
448 // the modtime needs to be truncated too.
449 modtime = modtime.Truncate(time.Second)
450 if ret := modtime.Compare(t); ret <= 0 {
456 func checkIfNoneMatch(w ResponseWriter, r *Request) condResult {
457 inm := r.Header.get("If-None-Match")
463 buf = textproto.TrimString(buf)
474 etag, remain := scanETag(buf)
478 if etagWeakMatch(etag, w.Header().get("Etag")) {
486 func checkIfModifiedSince(r *Request, modtime time.Time) condResult {
487 if r.Method != "GET" && r.Method != "HEAD" {
490 ims := r.Header.Get("If-Modified-Since")
491 if ims == "" || isZeroTime(modtime) {
494 t, err := ParseTime(ims)
498 // The Last-Modified header truncates sub-second precision so
499 // the modtime needs to be truncated too.
500 modtime = modtime.Truncate(time.Second)
501 if ret := modtime.Compare(t); ret <= 0 {
507 func checkIfRange(w ResponseWriter, r *Request, modtime time.Time) condResult {
508 if r.Method != "GET" && r.Method != "HEAD" {
511 ir := r.Header.get("If-Range")
515 etag, _ := scanETag(ir)
517 if etagStrongMatch(etag, w.Header().Get("Etag")) {
523 // The If-Range value is typically the ETag value, but it may also be
524 // the modtime date. See golang.org/issue/8367.
525 if modtime.IsZero() {
528 t, err := ParseTime(ir)
532 if t.Unix() == modtime.Unix() {
538 var unixEpochTime = time.Unix(0, 0)
540 // isZeroTime reports whether t is obviously unspecified (either zero or Unix()=0).
541 func isZeroTime(t time.Time) bool {
542 return t.IsZero() || t.Equal(unixEpochTime)
545 func setLastModified(w ResponseWriter, modtime time.Time) {
546 if !isZeroTime(modtime) {
547 w.Header().Set("Last-Modified", modtime.UTC().Format(TimeFormat))
551 func writeNotModified(w ResponseWriter) {
552 // RFC 7232 section 4.1:
553 // a sender SHOULD NOT generate representation metadata other than the
554 // above listed fields unless said metadata exists for the purpose of
555 // guiding cache updates (e.g., Last-Modified might be useful if the
556 // response does not have an ETag field).
558 delete(h, "Content-Type")
559 delete(h, "Content-Length")
560 delete(h, "Content-Encoding")
561 if h.Get("Etag") != "" {
562 delete(h, "Last-Modified")
564 w.WriteHeader(StatusNotModified)
567 // checkPreconditions evaluates request preconditions and reports whether a precondition
568 // resulted in sending StatusNotModified or StatusPreconditionFailed.
569 func checkPreconditions(w ResponseWriter, r *Request, modtime time.Time) (done bool, rangeHeader string) {
570 // This function carefully follows RFC 7232 section 6.
571 ch := checkIfMatch(w, r)
573 ch = checkIfUnmodifiedSince(r, modtime)
576 w.WriteHeader(StatusPreconditionFailed)
579 switch checkIfNoneMatch(w, r) {
581 if r.Method == "GET" || r.Method == "HEAD" {
585 w.WriteHeader(StatusPreconditionFailed)
589 if checkIfModifiedSince(r, modtime) == condFalse {
595 rangeHeader = r.Header.get("Range")
596 if rangeHeader != "" && checkIfRange(w, r, modtime) == condFalse {
599 return false, rangeHeader
602 // name is '/'-separated, not filepath.Separator.
603 func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
604 const indexPage = "/index.html"
606 // redirect .../index.html to .../
607 // can't use Redirect() because that would make the path absolute,
608 // which would be a problem running under StripPrefix
609 if strings.HasSuffix(r.URL.Path, indexPage) {
610 localRedirect(w, r, "./")
614 f, err := fs.Open(name)
616 msg, code := toHTTPError(err)
624 msg, code := toHTTPError(err)
630 // redirect to canonical path: / at end of directory url
631 // r.URL.Path always begins with /
634 if url[len(url)-1] != '/' {
635 localRedirect(w, r, path.Base(url)+"/")
639 if url[len(url)-1] == '/' {
640 localRedirect(w, r, "../"+path.Base(url))
648 // redirect if the directory name doesn't end in a slash
649 if url == "" || url[len(url)-1] != '/' {
650 localRedirect(w, r, path.Base(url)+"/")
654 // use contents of index.html for directory, if present
655 index := strings.TrimSuffix(name, "/") + indexPage
656 ff, err := fs.Open(index)
667 // Still a directory? (we didn't find an index.html file)
669 if checkIfModifiedSince(r, d.ModTime()) == condFalse {
673 setLastModified(w, d.ModTime())
678 // serveContent will check modification time
679 sizeFunc := func() (int64, error) { return d.Size(), nil }
680 serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, f)
683 // toHTTPError returns a non-specific HTTP error message and status code
684 // for a given non-nil error value. It's important that toHTTPError does not
685 // actually return err.Error(), since msg and httpStatus are returned to users,
686 // and historically Go's ServeContent always returned just "404 Not Found" for
687 // all errors. We don't want to start leaking information in error messages.
688 func toHTTPError(err error) (msg string, httpStatus int) {
689 if errors.Is(err, fs.ErrNotExist) {
690 return "404 page not found", StatusNotFound
692 if errors.Is(err, fs.ErrPermission) {
693 return "403 Forbidden", StatusForbidden
696 return "500 Internal Server Error", StatusInternalServerError
699 // localRedirect gives a Moved Permanently response.
700 // It does not convert relative paths to absolute paths like Redirect does.
701 func localRedirect(w ResponseWriter, r *Request, newPath string) {
702 if q := r.URL.RawQuery; q != "" {
705 w.Header().Set("Location", newPath)
706 w.WriteHeader(StatusMovedPermanently)
709 // ServeFile replies to the request with the contents of the named
710 // file or directory.
712 // If the provided file or directory name is a relative path, it is
713 // interpreted relative to the current directory and may ascend to
714 // parent directories. If the provided name is constructed from user
715 // input, it should be sanitized before calling ServeFile.
717 // As a precaution, ServeFile will reject requests where r.URL.Path
718 // contains a ".." path element; this protects against callers who
719 // might unsafely use filepath.Join on r.URL.Path without sanitizing
720 // it and then use that filepath.Join result as the name argument.
722 // As another special case, ServeFile redirects any request where r.URL.Path
723 // ends in "/index.html" to the same path, without the final
724 // "index.html". To avoid such redirects either modify the path or
727 // Outside of those two special cases, ServeFile does not use
728 // r.URL.Path for selecting the file or directory to serve; only the
729 // file or directory provided in the name argument is used.
730 func ServeFile(w ResponseWriter, r *Request, name string) {
731 if containsDotDot(r.URL.Path) {
732 // Too many programs use r.URL.Path to construct the argument to
733 // serveFile. Reject the request under the assumption that happened
734 // here and ".." may not be wanted.
735 // Note that name might not contain "..", for example if code (still
736 // incorrectly) used filepath.Join(myDir, r.URL.Path).
737 Error(w, "invalid URL path", StatusBadRequest)
740 dir, file := filepath.Split(name)
741 serveFile(w, r, Dir(dir), file, false)
744 // ServeFileFS replies to the request with the contents
745 // of the named file or directory from the file system fsys.
747 // If the provided file or directory name is a relative path, it is
748 // interpreted relative to the current directory and may ascend to
749 // parent directories. If the provided name is constructed from user
750 // input, it should be sanitized before calling ServeFile.
752 // As a precaution, ServeFile will reject requests where r.URL.Path
753 // contains a ".." path element; this protects against callers who
754 // might unsafely use filepath.Join on r.URL.Path without sanitizing
755 // it and then use that filepath.Join result as the name argument.
757 // As another special case, ServeFile redirects any request where r.URL.Path
758 // ends in "/index.html" to the same path, without the final
759 // "index.html". To avoid such redirects either modify the path or
762 // Outside of those two special cases, ServeFile does not use
763 // r.URL.Path for selecting the file or directory to serve; only the
764 // file or directory provided in the name argument is used.
765 func ServeFileFS(w ResponseWriter, r *Request, fsys fs.FS, name string) {
766 if containsDotDot(r.URL.Path) {
767 // Too many programs use r.URL.Path to construct the argument to
768 // serveFile. Reject the request under the assumption that happened
769 // here and ".." may not be wanted.
770 // Note that name might not contain "..", for example if code (still
771 // incorrectly) used filepath.Join(myDir, r.URL.Path).
772 Error(w, "invalid URL path", StatusBadRequest)
775 serveFile(w, r, FS(fsys), name, false)
778 func containsDotDot(v string) bool {
779 if !strings.Contains(v, "..") {
782 for _, ent := range strings.FieldsFunc(v, isSlashRune) {
790 func isSlashRune(r rune) bool { return r == '/' || r == '\\' }
792 type fileHandler struct {
804 func (f ioFS) Open(name string) (File, error) {
808 name = strings.TrimPrefix(name, "/")
810 file, err := f.fsys.Open(name)
812 return nil, mapOpenError(err, name, '/', func(path string) (fs.FileInfo, error) {
813 return fs.Stat(f.fsys, path)
816 return ioFile{file}, nil
819 func (f ioFile) Close() error { return f.file.Close() }
820 func (f ioFile) Read(b []byte) (int, error) { return f.file.Read(b) }
821 func (f ioFile) Stat() (fs.FileInfo, error) { return f.file.Stat() }
823 var errMissingSeek = errors.New("io.File missing Seek method")
824 var errMissingReadDir = errors.New("io.File directory missing ReadDir method")
826 func (f ioFile) Seek(offset int64, whence int) (int64, error) {
827 s, ok := f.file.(io.Seeker)
829 return 0, errMissingSeek
831 return s.Seek(offset, whence)
834 func (f ioFile) ReadDir(count int) ([]fs.DirEntry, error) {
835 d, ok := f.file.(fs.ReadDirFile)
837 return nil, errMissingReadDir
839 return d.ReadDir(count)
842 func (f ioFile) Readdir(count int) ([]fs.FileInfo, error) {
843 d, ok := f.file.(fs.ReadDirFile)
845 return nil, errMissingReadDir
847 var list []fs.FileInfo
849 dirs, err := d.ReadDir(count - len(list))
850 for _, dir := range dirs {
851 info, err := dir.Info()
853 // Pretend it doesn't exist, like (*os.File).Readdir does.
856 list = append(list, info)
861 if count < 0 || len(list) >= count {
868 // FS converts fsys to a FileSystem implementation,
869 // for use with FileServer and NewFileTransport.
870 // The files provided by fsys must implement io.Seeker.
871 func FS(fsys fs.FS) FileSystem {
875 // FileServer returns a handler that serves HTTP requests
876 // with the contents of the file system rooted at root.
878 // As a special case, the returned file server redirects any request
879 // ending in "/index.html" to the same path, without the final
882 // To use the operating system's file system implementation,
885 // http.Handle("/", http.FileServer(http.Dir("/tmp")))
887 // To use an fs.FS implementation, use http.FileServerFS instead.
888 func FileServer(root FileSystem) Handler {
889 return &fileHandler{root}
892 // FileServerFS returns a handler that serves HTTP requests
893 // with the contents of the file system fsys.
895 // As a special case, the returned file server redirects any request
896 // ending in "/index.html" to the same path, without the final
899 // http.Handle("/", http.FileServerFS(fsys))
900 func FileServerFS(root fs.FS) Handler {
901 return FileServer(FS(root))
904 func (f *fileHandler) ServeHTTP(w ResponseWriter, r *Request) {
906 if !strings.HasPrefix(upath, "/") {
910 serveFile(w, r, f.root, path.Clean(upath), true)
913 // httpRange specifies the byte range to be sent to the client.
914 type httpRange struct {
918 func (r httpRange) contentRange(size int64) string {
919 return fmt.Sprintf("bytes %d-%d/%d", r.start, r.start+r.length-1, size)
922 func (r httpRange) mimeHeader(contentType string, size int64) textproto.MIMEHeader {
923 return textproto.MIMEHeader{
924 "Content-Range": {r.contentRange(size)},
925 "Content-Type": {contentType},
929 // parseRange parses a Range header string as per RFC 7233.
930 // errNoOverlap is returned if none of the ranges overlap.
931 func parseRange(s string, size int64) ([]httpRange, error) {
933 return nil, nil // header not present
936 if !strings.HasPrefix(s, b) {
937 return nil, errors.New("invalid range")
939 var ranges []httpRange
941 for _, ra := range strings.Split(s[len(b):], ",") {
942 ra = textproto.TrimString(ra)
946 start, end, ok := strings.Cut(ra, "-")
948 return nil, errors.New("invalid range")
950 start, end = textproto.TrimString(start), textproto.TrimString(end)
953 // If no start is specified, end specifies the
954 // range start relative to the end of the file,
955 // and we are dealing with <suffix-length>
956 // which has to be a non-negative integer as per
957 // RFC 7233 Section 2.1 "Byte-Ranges".
958 if end == "" || end[0] == '-' {
959 return nil, errors.New("invalid range")
961 i, err := strconv.ParseInt(end, 10, 64)
962 if i < 0 || err != nil {
963 return nil, errors.New("invalid range")
969 r.length = size - r.start
971 i, err := strconv.ParseInt(start, 10, 64)
972 if err != nil || i < 0 {
973 return nil, errors.New("invalid range")
976 // If the range begins after the size of the content,
977 // then it does not overlap.
983 // If no end is specified, range extends to end of the file.
984 r.length = size - r.start
986 i, err := strconv.ParseInt(end, 10, 64)
987 if err != nil || r.start > i {
988 return nil, errors.New("invalid range")
993 r.length = i - r.start + 1
996 ranges = append(ranges, r)
998 if noOverlap && len(ranges) == 0 {
999 // The specified ranges did not overlap with the content.
1000 return nil, errNoOverlap
1005 // countingWriter counts how many bytes have been written to it.
1006 type countingWriter int64
1008 func (w *countingWriter) Write(p []byte) (n int, err error) {
1009 *w += countingWriter(len(p))
1013 // rangesMIMESize returns the number of bytes it takes to encode the
1014 // provided ranges as a multipart response.
1015 func rangesMIMESize(ranges []httpRange, contentType string, contentSize int64) (encSize int64) {
1016 var w countingWriter
1017 mw := multipart.NewWriter(&w)
1018 for _, ra := range ranges {
1019 mw.CreatePart(ra.mimeHeader(contentType, contentSize))
1020 encSize += ra.length
1027 func sumRangesSize(ranges []httpRange) (size int64) {
1028 for _, ra := range ranges {