当前位置: 首页>>代码示例>>Golang>>正文


Golang FileSystem.Open方法代码示例

本文整理汇总了Golang中net/http.FileSystem.Open方法的典型用法代码示例。如果您正苦于以下问题:Golang FileSystem.Open方法的具体用法?Golang FileSystem.Open怎么用?Golang FileSystem.Open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.FileSystem的用法示例。


在下文中一共展示了FileSystem.Open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ServeFile

// ServeFile responds to w with the contents of path within fs.
func ServeFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, path string) {

	// Open file handle.
	f, err := fs.Open(path)
	if err != nil {
		http.Error(w, "404 Not Found", 404)
		return
	}
	defer f.Close()

	// Make sure path exists.
	fileinfo, err1 := f.Stat()
	if err1 != nil {
		http.Error(w, "404 Not Found", 404)
		return
	}

	// Reject directory requests.
	if fileinfo.IsDir() {
		http.Error(w, "403 Forbidden", 403)
		return
	}

	http.ServeContent(w, r, fileinfo.Name(), fileinfo.ModTime(), f)

}
开发者ID:strukturag,项目名称:httputils,代码行数:27,代码来源:file.go

示例2: serveFile

func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string) {
	f, err := fs.Open(name)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	defer util.Close(f)

	d, err1 := f.Stat()
	if err1 != nil {
		http.NotFound(w, r)
		return
	}

	url := r.URL.Path
	if d.IsDir() {
		if url[len(url)-1] != '/' {
			w.Header().Set("Location", path.Base(url)+"/")
			w.WriteHeader(http.StatusMovedPermanently)
			return
		}
		glog.Infof("Dir List: %s", name)
		dirList(w, f)
		return
	}

	http.ServeContent(w, r, d.Name(), d.ModTime(), f)
}
开发者ID:kleopatra999,项目名称:skia-buildbot,代码行数:28,代码来源:main.go

示例3: StaticMiddlewareFromDir

// StaticMiddlewareFromDir returns a middleware that serves static files from the specified http.FileSystem.
// This middleware is great for development because each file is read from disk each time and no
// special caching or cache headers are sent.
//
// If a path is requested which maps to a folder with an index.html folder on your filesystem,
// then that index.html file will be served.
func StaticMiddlewareFromDir(dir http.FileSystem, options ...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) {
	var option StaticOption
	if len(options) > 0 {
		option = options[0]
	}
	return func(w ResponseWriter, req *Request, next NextMiddlewareFunc) {
		if req.Method != "GET" && req.Method != "HEAD" {
			next(w, req)
			return
		}

		file := req.URL.Path
		if option.Prefix != "" {
			if !strings.HasPrefix(file, option.Prefix) {
				next(w, req)
				return
			}
			file = file[len(option.Prefix):]
		}

		f, err := dir.Open(file)
		if err != nil {
			next(w, req)
			return
		}
		defer f.Close()

		fi, err := f.Stat()
		if err != nil {
			next(w, req)
			return
		}

		// If the file is a directory, try to serve an index file.
		// If no index is available, DO NOT serve the directory to avoid
		// Content-Length issues. Simply skip to the next middleware, and return
		// a 404 if no path with the same name is handled.
		if fi.IsDir() {
			if option.IndexFile != "" {
				file = filepath.Join(file, option.IndexFile)
				f, err = dir.Open(file)
				if err != nil {
					next(w, req)
					return
				}
				defer f.Close()

				fi, err = f.Stat()
				if err != nil || fi.IsDir() {
					next(w, req)
					return
				}
			} else {
				next(w, req)
				return
			}
		}
		http.ServeContent(w, req.Request, file, fi.ModTime(), f)
	}
}
开发者ID:plorefice,项目名称:web,代码行数:66,代码来源:static_middleware.go

示例4: serveFile

// name is '/'-separated, not filepath.Separator.
func (f *fileHandler) serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string, redirect bool) {
	looper += 1
	if looper > 10 {
		panic("TILT")
	}
	const indexPage = "/index.html"

	debug("opening %s from fs", name)
	file, err := fs.Open(name)
	if err != nil {
		if os.IsNotExist(err) {
			if !testIfFile.MatchString(name) {
				f.serveFile(w, r, fs, ".", redirect)
				return
			}
		}
		msg, code := toHTTPError(err)
		http.Error(w, msg, code)
		return
	}
	defer file.Close()

	debug("getting stat")
	d, err1 := file.Stat()
	if err1 != nil {
		if os.IsNotExist(err1) {
			if !testIfFile.MatchString(name) {
				f.serveFile(w, r, fs, f.rootDir, redirect)
				return
			}
		}
		msg, code := toHTTPError(err1)
		http.Error(w, msg, code)
		return
	}

	// use contents of index.html for directory, if present
	if d.IsDir() {
		index := strings.TrimSuffix(name, "/") + indexPage
		ff, err := fs.Open(index)
		if err == nil {
			defer ff.Close()
			dd, err := ff.Stat()
			if err == nil {
				name = index
				d = dd
				file = ff
			}
		}
	}

	// Still a directory? (we didn't find an index.html file)
	if d.IsDir() {
		f.serveFile(w, r, fs, ".", redirect)
	}

	// serveContent will check modification time
	sizeFunc := func() (int64, error) { return d.Size(), nil }
	f.serveContent(w, r, d.Name(), d.ModTime(), sizeFunc, file)
}
开发者ID:dangersalad,项目名称:spaserver,代码行数:61,代码来源:server.go

示例5: serveFile

func serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string) {
	f, err := fs.Open(name)
	if err != nil {
		http.NotFound(w, r)
		return
	}
	defer f.Close()

	d, err1 := f.Stat()
	if err1 != nil {
		http.NotFound(w, r)
		return
	}

	if d.IsDir() {
		// Directory, list the contents
		dirList(w, f)
	} else {
		// Actually playback a recording
		offset, err := time.ParseDuration(r.FormValue("offset"))
		if err != nil {
			log.Error("parse offset: %v: %v", err, r.FormValue("offset"))
			offset = 0
		}

		streamRecording(w, f, offset)
	}
}
开发者ID:cdshann,项目名称:minimega,代码行数:28,代码来源:server.go

示例6: serveFile

func (ms middlewareStatic) serveFile(w http.ResponseWriter, r *http.Request, fs http.FileSystem, name string) (err error) {
	f, err := fs.Open(name)
	if err != nil {
		return
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		return ErrFileNotFound
	}

	if d.IsDir() {
		f.Close()
		f, err = fs.Open(name + "/index.html")
		if err != nil {
			return
		}

		d, err = f.Stat()
		if err != nil {
			return ErrFileNotFound
		}

		if d.IsDir() {
			return ErrFileNotFound
		}
	}

	http.ServeContent(w, r, d.Name(), d.ModTime(), f)
	return nil
}
开发者ID:hypertornado,项目名称:prago,代码行数:32,代码来源:static.go

示例7: ExampleReadTwoOpenedUncompressedFiles

func ExampleReadTwoOpenedUncompressedFiles() {
	var fs http.FileSystem = assets

	f0, err := fs.Open("/not-worth-compressing-file.txt")
	if err != nil {
		panic(err)
	}
	defer f0.Close()
	_ = f0.(notWorthGzipCompressing)
	f1, err := fs.Open("/not-worth-compressing-file.txt")
	if err != nil {
		panic(err)
	}
	defer f1.Close()
	_ = f1.(notWorthGzipCompressing)

	_, err = io.CopyN(os.Stdout, f0, 9)
	if err != nil {
		panic(err)
	}
	_, err = io.CopyN(os.Stdout, f1, 9)
	if err != nil {
		panic(err)
	}

	// Output:
	// Its normaIts norma
}
开发者ID:pombredanne,项目名称:vfsgen,代码行数:28,代码来源:test_test.go

示例8: MaybeGzip

// Looks for a file.gz file and serves that if present
// `original` is a file server
func MaybeGzip(root http.FileSystem, original http.Handler) http.Handler {
	return http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		if strings.Contains(request.Header.Get("Accept-Encoding"), "gzip") {
			requestPath := request.URL.Path
			if !strings.HasPrefix(requestPath, "/") {
				requestPath = "/" + requestPath
			}
			requestPath = path.Clean(requestPath)
			gzPath := requestPath + ".gz"
			if requestPath == "/" {
				gzPath = "/index.html.gz"
			}
			// log.Print(gzPath)
			file, err := root.Open(gzPath)
			if err == nil {
				file.Close()
				contentType := mime.TypeByExtension(filepath.Ext(requestPath))
				if contentType == "" {
					contentType = "text/html; charset=utf-8"
				}
				response.Header().Set("Content-Type", contentType)
				response.Header().Set("Content-Encoding", "gzip")
				request.URL.Path = gzPath
			}
		}
		original.ServeHTTP(response, request)
	})
}
开发者ID:jeisc,项目名称:sneakynote.com,代码行数:30,代码来源:handlers.go

示例9: ContextInclude

// ContextInclude opens filename using fs and executes a template with the context ctx.
// This does the same thing that Context.Include() does, but with the ability to provide
// your own context so that the included files can have access to additional fields your
// type may provide. You can embed Context in your type, then override its Include method
// to call this function with ctx being the instance of your type, and fs being Context.Root.
func ContextInclude(filename string, ctx interface{}, fs http.FileSystem) (string, error) {
	file, err := fs.Open(filename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	body, err := ioutil.ReadAll(file)
	if err != nil {
		return "", err
	}

	tpl, err := template.New(filename).Parse(string(body))
	if err != nil {
		return "", err
	}

	var buf bytes.Buffer
	err = tpl.Execute(&buf, ctx)
	if err != nil {
		return "", err
	}

	return buf.String(), nil
}
开发者ID:klauern,项目名称:caddy,代码行数:30,代码来源:context.go

示例10: ExampleReadTwoOpenedCompressedFiles

func ExampleReadTwoOpenedCompressedFiles() {
	var fs http.FileSystem = assets

	f0, err := fs.Open("/sample-file.txt")
	if err != nil {
		panic(err)
	}
	defer f0.Close()
	_ = f0.(gzipByter)
	f1, err := fs.Open("/sample-file.txt")
	if err != nil {
		panic(err)
	}
	defer f1.Close()
	_ = f1.(gzipByter)

	_, err = io.CopyN(os.Stdout, f0, 9)
	if err != nil {
		panic(err)
	}
	_, err = io.CopyN(os.Stdout, f1, 9)
	if err != nil {
		panic(err)
	}

	// Output:
	// This fileThis file
}
开发者ID:pombredanne,项目名称:vfsgen,代码行数:28,代码来源:test_test.go

示例11: serveFile

// @ modified by henrylee2cn 2016.1.22
func (e *Echo) serveFile(fs http.FileSystem, file string, c *Context) (err error) {
	f, err := fs.Open(file)
	if err != nil {
		return NewHTTPError(http.StatusNotFound)
	}
	defer f.Close()

	fi, _ := f.Stat()
	if fi.IsDir() {
		/* NOTE:
		Not checking the Last-Modified header as it caches the response `304` when
		changing differnt directories for the same path.
		*/
		d := f

		// Index file
		file = filepath.Join(file, indexPage)
		f, err = fs.Open(file)
		if err != nil {
			if e.autoIndex {
				// Auto index
				return listDir(d, c)
			}
			return NewHTTPError(http.StatusForbidden)
		}
		fi, _ = f.Stat() // Index file stat
	}

	http.ServeContent(c.response, c.request, fi.Name(), fi.ModTime(), f)
	return
}
开发者ID:henrylee2cn,项目名称:thinkgo,代码行数:32,代码来源:echo.go

示例12: ExampleCompressed

func ExampleCompressed() {
	// Compressed file system.
	var fs http.FileSystem = assets

	walkFn := func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			log.Printf("can't stat file %s: %v\n", path, err)
			return nil
		}

		fmt.Println(path)
		if fi.IsDir() {
			return nil
		}

		f, err := fs.Open(path)
		if err != nil {
			fmt.Printf("fs.Open(%q): %v\n", path, err)
			return nil
		}
		defer f.Close()

		b, err := ioutil.ReadAll(f)
		fmt.Printf("%q %v\n", string(b), err)

		if gzipFile, ok := f.(gzipByter); ok {
			b := gzipFile.GzipBytes()
			fmt.Printf("%q\n", string(b))
		} else {
			fmt.Println("<not compressed>")
		}
		return nil
	}

	err := vfsutil.Walk(fs, "/", walkFn)
	if err != nil {
		panic(err)
	}

	// Output:
	// /
	// /folderA
	// /folderA/file1.txt
	// "Stuff in /folderA/file1.txt." <nil>
	// <not compressed>
	// /folderA/file2.txt
	// "Stuff in /folderA/file2.txt." <nil>
	// <not compressed>
	// /folderB
	// /folderB/folderC
	// /folderB/folderC/file3.txt
	// "Stuff in /folderB/folderC/file3.txt." <nil>
	// <not compressed>
	// /not-worth-compressing-file.txt
	// "Its normal contents are here." <nil>
	// <not compressed>
	// /sample-file.txt
	// "This file compresses well. Blaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah!" <nil>
	// "\x1f\x8b\b\x00\x00\tn\x88\x00\xff\n\xc9\xc8,VH\xcb\xccIUH\xce\xcf-(J-.N-V(O\xcd\xc9\xd1Sp\xcaI\x1c\xd4 C\x11\x10\x00\x00\xff\xff\xe7G\x81:\xbd\x00\x00\x00"
}
开发者ID:pombredanne,项目名称:vfsgen,代码行数:60,代码来源:test_test.go

示例13: Stat

// Stat returns the FileInfo structure describing file.
func Stat(fs http.FileSystem, name string) (os.FileInfo, error) {
	f, err := fs.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return f.Stat()
}
开发者ID:bg451,项目名称:appdash,代码行数:9,代码来源:vfsutil.go

示例14: ReadDir

// ReadDir reads the contents of the directory associated with file and
// returns a slice of FileInfo values in directory order.
func ReadDir(fs http.FileSystem, name string) ([]os.FileInfo, error) {
	f, err := fs.Open(name)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	return f.Readdir(0)
}
开发者ID:bg451,项目名称:appdash,代码行数:10,代码来源:vfsutil.go

示例15: ReadFile

// ReadFile reads the file named by path from fs and returns the contents.
func ReadFile(fs http.FileSystem, path string) ([]byte, error) {
	rc, err := fs.Open(path)
	if err != nil {
		return nil, err
	}
	defer rc.Close()
	return ioutil.ReadAll(rc)
}
开发者ID:bg451,项目名称:appdash,代码行数:9,代码来源:vfsutil.go


注:本文中的net/http.FileSystem.Open方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。