github.com/bosssauce/ponzu@v0.11.1-0.20200102001432-9bc41b703131/system/admin/filesystem.go (about)

     1  package admin
     2  
     3  import (
     4  	"encoding/json"
     5  	"net/http"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/ponzu-cms/ponzu/system/db"
    11  	"github.com/ponzu-cms/ponzu/system/item"
    12  )
    13  
    14  func deleteUploadFromDisk(target string) error {
    15  	// get data on file
    16  	data, err := db.Upload(target)
    17  	if err != nil {
    18  		return err
    19  	}
    20  
    21  	// unmarshal data
    22  	upload := item.FileUpload{}
    23  	if err = json.Unmarshal(data, &upload); err != nil {
    24  		return err
    25  	}
    26  
    27  	// split and rebuild path in OS friendly way
    28  	// use path to delete the physical file from disk
    29  	pathSplit := strings.Split(strings.TrimPrefix(upload.Path, "/api/"), "/")
    30  	pathJoin := filepath.Join(pathSplit...)
    31  	err = os.Remove(pathJoin)
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	return nil
    37  }
    38  
    39  func restrict(dir http.Dir) justFilesFilesystem {
    40  	return justFilesFilesystem{dir}
    41  }
    42  
    43  // the code below removes the open directory listing when accessing a URL which
    44  // normally would point to a directory. code from golang-nuts mailing list:
    45  // https://groups.google.com/d/msg/golang-nuts/bStLPdIVM6w/hidTJgDZpHcJ
    46  // credit: Brad Fitzpatrick (c) 2012
    47  
    48  type justFilesFilesystem struct {
    49  	fs http.FileSystem
    50  }
    51  
    52  func (fs justFilesFilesystem) Open(name string) (http.File, error) {
    53  	f, err := fs.fs.Open(name)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	return neuteredReaddirFile{f}, nil
    58  }
    59  
    60  type neuteredReaddirFile struct {
    61  	http.File
    62  }
    63  
    64  func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
    65  	return nil, nil
    66  }