Add file helper

This commit is contained in:
Dane Everitt 2020-12-25 13:57:26 -08:00
parent 5c78cb9ab3
commit d96115325a
No known key found for this signature in database
GPG Key ID: EEA66103B3D71F53
2 changed files with 27 additions and 19 deletions

View File

@ -22,7 +22,7 @@ import (
// Returns the contents of a file on the server.
func getServerFileContents(c *gin.Context) {
s := GetServer(c.Param("server"))
s := ExtractServer(c)
f, err := url.QueryUnescape(c.Query("file"))
if err != nil {
WithError(c, err)
@ -31,7 +31,7 @@ func getServerFileContents(c *gin.Context) {
p := "/" + strings.TrimLeft(f, "/")
st, err := s.Filesystem().Stat(p)
if err != nil {
NewServerError(err, s).AbortFilesystemError(c)
WithError(c, err)
return
}
@ -55,9 +55,10 @@ func getServerFileContents(c *gin.Context) {
// happen since we're doing so much before this point that would normally throw an error if there
// was a problem with the file.
if err := s.Filesystem().Readfile(p, c.Writer); err != nil {
NewServerError(err, s).AbortFilesystemError(c)
WithError(c, err)
return
}
c.Writer.Flush()
}
// Returns the contents of a directory for a server.

View File

@ -50,29 +50,36 @@ func (fs *Filesystem) Path() string {
return fs.root
}
// Returns a reader for a file instance.
func (fs *Filesystem) File(p string) (*os.File, os.FileInfo, error) {
cleaned, err := fs.SafePath(p)
if err != nil {
return nil, nil, err
}
st, err := os.Stat(cleaned)
if err != nil {
return nil, nil, err
}
if st.IsDir() {
return nil, nil, &Error{code: ErrCodeIsDirectory}
}
f, err := os.Open(cleaned)
if err != nil {
return nil, nil, err
}
return f, st, nil
}
// Reads a file on the system and returns it as a byte representation in a file
// reader. This is not the most memory efficient usage since it will be reading the
// entirety of the file into memory.
func (fs *Filesystem) Readfile(p string, w io.Writer) error {
cleaned, err := fs.SafePath(p)
file, _, err := fs.File(p)
if err != nil {
return err
}
if st, err := os.Stat(cleaned); err != nil {
return err
} else if st.IsDir() {
return &Error{code: ErrCodeIsDirectory}
}
f, err := os.Open(cleaned)
if err != nil {
return err
}
defer f.Close()
_, err = bufio.NewReader(f).WriteTo(w)
defer file.Close()
_, err = bufio.NewReader(file).WriteTo(w)
return err
}