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