本文整理汇总了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)
}
示例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)
}
示例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)
}
}
示例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)
}
示例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)
}
}
示例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
}
示例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
}
示例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)
})
}
示例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
}
示例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
}
示例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
}
示例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"
}
示例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()
}
示例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)
}
示例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)
}