...

Source file src/code.rocketnine.space/tslocum/gmitohtml/pkg/gmitohtml/fs.go

Documentation: code.rocketnine.space/tslocum/gmitohtml/pkg/gmitohtml

     1  package gmitohtml
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  	"os"
     7  	"time"
     8  )
     9  
    10  var modTime = time.Now()
    11  
    12  type inMemoryFS map[string]http.File
    13  
    14  func (fs inMemoryFS) Open(name string) (http.File, error) {
    15  	if f, ok := fs[name]; ok {
    16  		f.Seek(0, io.SeekStart)
    17  		return f, nil
    18  	}
    19  	panic("No file")
    20  }
    21  
    22  type inMemoryFile struct {
    23  	at   int64
    24  	Name string
    25  	data []byte
    26  	fs   inMemoryFS
    27  }
    28  
    29  func loadFile(name string, val string, fs inMemoryFS) *inMemoryFile {
    30  	return &inMemoryFile{at: 0,
    31  		Name: name,
    32  		data: []byte(val),
    33  		fs:   fs}
    34  }
    35  
    36  func (f *inMemoryFile) Close() error {
    37  	return nil
    38  }
    39  func (f *inMemoryFile) Stat() (os.FileInfo, error) {
    40  	return &inMemoryFileInfo{f}, nil
    41  }
    42  func (f *inMemoryFile) Readdir(count int) ([]os.FileInfo, error) {
    43  	res := make([]os.FileInfo, len(f.fs))
    44  	i := 0
    45  	for _, file := range f.fs {
    46  		res[i], _ = file.Stat()
    47  		i++
    48  	}
    49  	return res, nil
    50  }
    51  func (f *inMemoryFile) Read(b []byte) (int, error) {
    52  	i := 0
    53  	for f.at < int64(len(f.data)) && i < len(b) {
    54  		b[i] = f.data[f.at]
    55  		i++
    56  		f.at++
    57  	}
    58  	return i, nil
    59  }
    60  func (f *inMemoryFile) Seek(offset int64, whence int) (int64, error) {
    61  	switch whence {
    62  	case 0:
    63  		f.at = offset
    64  	case 1:
    65  		f.at += offset
    66  	case 2:
    67  		f.at = int64(len(f.data)) + offset
    68  	}
    69  	return f.at, nil
    70  }
    71  
    72  type inMemoryFileInfo struct {
    73  	file *inMemoryFile
    74  }
    75  
    76  func (s *inMemoryFileInfo) Name() string       { return s.file.Name }
    77  func (s *inMemoryFileInfo) Size() int64        { return int64(len(s.file.data)) }
    78  func (s *inMemoryFileInfo) Mode() os.FileMode  { return os.ModeTemporary }
    79  func (s *inMemoryFileInfo) ModTime() time.Time { return modTime }
    80  func (s *inMemoryFileInfo) IsDir() bool        { return false }
    81  func (s *inMemoryFileInfo) Sys() interface{}   { return nil }
    82  

View as plain text