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


Golang http.File类代码示例

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


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

示例1: dirList

func dirList(w http.ResponseWriter, f http.File, name string) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(w, "<pre>\n")
	switch name {
	case "/":
		fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", "/", ".")
	default:
		fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", path.Clean(name+"/.."), "..")
	}
	for {
		dirs, err := f.Readdir(100)
		if err != nil || len(dirs) == 0 {
			break
		}
		sort.Sort(byName(dirs))
		for _, d := range dirs {
			name := d.Name()
			if d.IsDir() {
				name += "/"
			}
			// name may contain '?' or '#', which must be escaped to remain
			// part of the URL path, and not indicate the start of a query
			// string or fragment.
			url := url.URL{Path: name}
			fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), html.EscapeString(name))
		}
	}
	fmt.Fprintf(w, "</pre>\n")
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:29,代码来源:gzip_file_server.go

示例2: readFile

func readFile(f http.File) (chan *FramebufferUpdate, error) {
	gzipReader, err := gzip.NewReader(f)
	if err != nil {
		return nil, err
	}
	bufioReader := bufio.NewReader(gzipReader)
	reader := NewRecordingReader(bufioReader)
	output := make(chan *FramebufferUpdate)

	go func() {
		defer f.Close()
		defer close(output)

		var err error
		for err == nil {
			err = readUpdate(reader, output)
		}

		if err != nil && err != io.EOF {
			log.Errorln("error decoding recording:", err)
		}
	}()

	return output, nil
}
开发者ID:npe9,项目名称:minimega,代码行数:25,代码来源:main.go

示例3: dirList

func dirList(w http.ResponseWriter, f http.File) {
	dirs, err := f.Readdir(-1)
	if err != nil {
		// TODO: log err.Error() to the Server.ErrorLog, once it's possible
		// for a handler to get at its Server via the ResponseWriter. See
		// Issue 12438.
		http.Error(w, "Error reading directory", http.StatusInternalServerError)
		return
	}
	sort.Sort(byName(dirs))

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(w, "<pre>\n")
	for _, d := range dirs {
		name := d.Name()
		if d.IsDir() {
			name += "/"
		}
		// name may contain '?' or '#', which must be escaped to remain
		// part of the URL path, and not indicate the start of a query
		// string or fragment.
		url := url.URL{Path: name}
		fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
	}
	fmt.Fprintf(w, "</pre>\n")
}
开发者ID:dangersalad,项目名称:spaserver,代码行数:26,代码来源:server.go

示例4: dirList

func dirList(ci inject.CopyInject, logger termlog.Logger, w http.ResponseWriter, name string, f http.File, templates *template.Template) {
	w.Header().Set("Cache-Control", "no-store, must-revalidate")
	files, err := f.Readdir(0)
	if err != nil {
		logger.Shout("Error reading directory for listing: %s", err)
		return
	}
	data := dirData{Name: name, Files: files}
	buff := bytes.NewBuffer(make([]byte, 0, 0))
	err = templates.Lookup("dirlist.html").Execute(buff, data)
	length := buff.Len()
	if err != nil {
		logger.Shout("Error producing directory listing: %s", err)
	}
	inj, err := ci.Sniff(buff)
	if err != nil {
		logger.Shout("Failed to inject in dir listing: %s", err)
		return
	}
	w.Header().Set(
		"Content-Length", fmt.Sprintf("%d", length+inj.Extra()),
	)
	_, err = inj.Copy(w)
	if err != nil {
		logger.Shout("Failed to inject in dir listing: %s", err)
		return
	}
}
开发者ID:npk,项目名称:devd,代码行数:28,代码来源:fileserver.go

示例5: servefile

func servefile(c *ctx, f http.File) error {
	fi, err := f.Stat()
	if err == nil {
		http.ServeContent(c.RW, c.Request, fi.Name(), fi.ModTime(), f)
	}
	return err
}
开发者ID:maiconio,项目名称:flotilla,代码行数:7,代码来源:extensions.go

示例6: NewFromHTTPFile

// NewFromHTTPFile returns  new *StaticFile from f
func NewFromHTTPFile(f http.File) (*StaticFile, error) {
	info, err := f.Stat()
	if err != nil {
		return nil, err
	}
	b, _ := ioutil.ReadAll(f)
	return &StaticFile{rsc: bytes.NewReader(b), info: info}, nil
}
开发者ID:gernest,项目名称:helen,代码行数:9,代码来源:file.go

示例7: serveContent

func serveContent(w http.ResponseWriter, r *http.Request, f http.File, fname string) {
	var modtime time.Time
	if fi, err := f.Stat(); err != nil {
		modtime = fi.ModTime()
	}

	http.ServeContent(w, r, fname, modtime, f)
}
开发者ID:jmptrader,项目名称:go-webapp-skeleton,代码行数:8,代码来源:serve.go

示例8: readAllFiles

func readAllFiles(file http.File) ([]os.FileInfo, error) {
	files := []os.FileInfo{}
	for {
		more, err := file.Readdir(100)
		if err == io.EOF {
			return files, nil
		} else if err != nil {
			return nil, err
		}
		files = append(files, more...)
	}
}
开发者ID:holizz,项目名称:srv,代码行数:12,代码来源:server.go

示例9: dirList

func dirList(ci inject.CopyInject, logger termlog.Logger, w http.ResponseWriter, name string, f http.File, templates *template.Template) {
	w.Header().Set("Cache-Control", "no-store, must-revalidate")
	files, err := f.Readdir(0)
	if err != nil {
		logger.Shout("Error reading directory for listing: %s", err)
		return
	}
	data := dirData{Name: name, Files: files}
	err = ci.ServeTemplate(http.StatusOK, w, templates.Lookup("dirlist.html"), data)
	if err != nil {
		logger.Shout("Failed to generate dir listing: %s", err)
	}
}
开发者ID:rawbite,项目名称:devd,代码行数:13,代码来源:fileserver.go

示例10: setContentType

func setContentType(w http.ResponseWriter, name string, file http.File) {
	t := mime.TypeByExtension(filepath.Ext(name))
	if t == "" {
		var buffer [512]byte
		n, _ := io.ReadFull(file, buffer[:])
		t = http.DetectContentType(buffer[:n])
		if _, err := file.Seek(0, os.SEEK_SET); err != nil {
			http.Error(w, "Can't seek", http.StatusInternalServerError)
			return
		}
	}
	w.Header().Set("Content-Type", t)
}
开发者ID:joaodasilva,项目名称:go-gzip-file-server,代码行数:13,代码来源:handler.go

示例11: Server

// Server returns a handler that serves the files as the response content.
// The files being served are determined using the current URL path and the specified path map.
// For example, if the path map is {"/css": "/www/css", "/js": "/www/js"} and the current URL path
// "/css/main.css", the file "<working dir>/www/css/main.css" will be served.
// If a URL path matches multiple prefixes in the path map, the most specific prefix will take precedence.
// For example, if the path map contains both "/css" and "/css/img", and the URL path is "/css/img/logo.gif",
// then the path mapped by "/css/img" will be used.
//
//     import (
//         "log"
//         "github.com/go-ozzo/ozzo-routing"
//         "github.com/go-ozzo/ozzo-routing/file"
//     )
//
//     r := routing.New()
//     r.Get("/*", file.Server(file.PathMap{
//          "/css": "/ui/dist/css",
//          "/js": "/ui/dist/js",
//     }))
func Server(pathMap PathMap, opts ...ServerOptions) routing.Handler {
	var options ServerOptions
	if len(opts) > 0 {
		options = opts[0]
	}
	if !filepath.IsAbs(options.RootPath) {
		options.RootPath = filepath.Join(RootPath, options.RootPath)
	}
	from, to := parsePathMap(pathMap)

	// security measure: limit the files within options.RootPath
	dir := http.Dir(options.RootPath)

	return func(c *routing.Context) error {
		if c.Request.Method != "GET" && c.Request.Method != "HEAD" {
			return routing.NewHTTPError(http.StatusMethodNotAllowed)
		}
		path, found := matchPath(c.Request.URL.Path, from, to)
		if !found || options.Allow != nil && !options.Allow(c, path) {
			return routing.NewHTTPError(http.StatusNotFound)
		}

		var (
			file  http.File
			fstat os.FileInfo
			err   error
		)

		if file, err = dir.Open(path); err != nil {
			if options.CatchAllFile != "" {
				return serveFile(c, dir, options.CatchAllFile)
			}
			return routing.NewHTTPError(http.StatusNotFound, err.Error())
		}
		defer file.Close()

		if fstat, err = file.Stat(); err != nil {
			return routing.NewHTTPError(http.StatusNotFound, err.Error())
		}

		if fstat.IsDir() {
			if options.IndexFile == "" {
				return routing.NewHTTPError(http.StatusNotFound)
			}
			return serveFile(c, dir, filepath.Join(path, options.IndexFile))
		}

		http.ServeContent(c.Response, c.Request, path, fstat.ModTime(), file)
		return nil
	}
}
开发者ID:go-ozzo,项目名称:ozzo-routing,代码行数:70,代码来源:server.go

示例12: dirList

func dirList(w http.ResponseWriter, f http.File, fs Filesystemhttp, name string, prefix string, auth bool) {
	//w.Header().Set("Content-Type", "text/html; charset=utf-8")
	//fmt.Fprintf(w, "<pre>\n")

	//finfo, _ := f.Stat()

	out := make(map[string]interface{})
	out["prefix"] = prefix
	out["path"] = name
	out["auth"] = auth

	authRead := auth || (!auth && !fs.ReadNeedsAuth)
	authList := auth || (!auth && !fs.ListNeedsAuth)
	authZip := auth || (!auth && !fs.ZipNeedsAuth)
	authDelete := auth || (!auth && !fs.DeleteNeedsAuth)
	authUpload := auth || (!auth && !fs.UploadNeedsAuth)
	authCreateFolder := auth || (!auth && !fs.CreateFolderNeedsAuth)

	out["authRead"] = authRead
	out["authList"] = authList
	out["authZip"] = authZip
	out["authDelete"] = authDelete
	out["authUpload"] = authUpload
	out["authCreateFolder"] = authCreateFolder

	if authList {
		files := make([]os.FileInfo, 0, 50)

		for {
			dirs, err := f.Readdir(100)
			if err != nil || len(dirs) == 0 {
				break
			}
			for _, d := range dirs {
				name := d.Name()
				if d.IsDir() {
					name += "/"
				}
				files = append(files, d)
			}
		}
		out["files"] = files
	}

	Template(TemplateFiles).Execute(w, out)

	//fmt.Fprintf(w, "</pre>\n")
}
开发者ID:ylmbtm,项目名称:nitori-go,代码行数:48,代码来源:http_file.go

示例13: dirList

func dirList(w http.ResponseWriter, f http.File) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	fmt.Fprintf(w, "<pre>\n")
	for {
		dirs, err := f.Readdir(100)
		if err != nil || len(dirs) == 0 {
			break
		}
		for _, d := range dirs {
			name := d.Name()
			if d.IsDir() {
				name += "/"
			}
			escaped := html.EscapeString(name)
			fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", escaped, escaped)
		}
	}
	fmt.Fprintf(w, "</pre>\n")
}
开发者ID:joaodasilva,项目名称:go-gzip-file-server,代码行数:19,代码来源:handler.go

示例14: serveGzippedFile

func (s *Server) serveGzippedFile(w http.ResponseWriter, r *http.Request, filename string, cache bool) {
	dir := http.Dir(s.staticPath)
	var err error
	var f http.File
	gzipped := false

	if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
		f, err = dir.Open(filename + ".gz")
		if err != nil {
			f = nil
		} else {
			gzipped = true
		}
	}

	if f == nil {
		f, err = dir.Open(filename)
		if err != nil {
			http.NotFound(w, r)
			return
		}
	}

	defer f.Close()

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

	name := d.Name()
	if gzipped {
		name = strings.TrimSuffix(name, ".gz")
		w = &gzipResponseWriter{
			ResponseWriter: w,
			cache:          cache,
		}
	}

	http.ServeContent(w, r, name, d.ModTime(), f)
}
开发者ID:logan,项目名称:heim,代码行数:42,代码来源:server.go

示例15: loadDirectoryContents

func (b Browse) loadDirectoryContents(requestedFilepath http.File, urlPath string) (*Listing, bool, error) {
	files, err := requestedFilepath.Readdir(-1)
	if err != nil {
		return nil, false, err
	}

	// Determine if user can browse up another folder
	var canGoUp bool
	curPathDir := path.Dir(strings.TrimSuffix(urlPath, "/"))
	for _, other := range b.Configs {
		if strings.HasPrefix(curPathDir, other.PathScope) {
			canGoUp = true
			break
		}
	}

	// Assemble listing of directory contents
	listing, hasIndex := directoryListing(files, canGoUp, urlPath)

	return &listing, hasIndex, nil
}
开发者ID:FiloSottile,项目名称:caddy,代码行数:21,代码来源:browse.go


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