github.com/gogf/gf@v1.16.9/os/gres/gres_file.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gres
     8  
     9  import (
    10  	"archive/zip"
    11  	"bytes"
    12  	"github.com/gogf/gf/internal/json"
    13  	"io"
    14  	"os"
    15  )
    16  
    17  type File struct {
    18  	file     *zip.File
    19  	reader   *bytes.Reader
    20  	resource *Resource
    21  }
    22  
    23  // Name returns the name of the file.
    24  func (f *File) Name() string {
    25  	return f.file.Name
    26  }
    27  
    28  // Open returns a ReadCloser that provides access to the File's contents.
    29  // Multiple files may be read concurrently.
    30  func (f *File) Open() (io.ReadCloser, error) {
    31  	return f.file.Open()
    32  }
    33  
    34  // Content returns the content of the file.
    35  func (f *File) Content() []byte {
    36  	reader, err := f.Open()
    37  	if err != nil {
    38  		return nil
    39  	}
    40  	defer reader.Close()
    41  	buffer := bytes.NewBuffer(nil)
    42  	if _, err := io.Copy(buffer, reader); err != nil {
    43  		return nil
    44  	}
    45  	return buffer.Bytes()
    46  }
    47  
    48  // FileInfo returns an os.FileInfo for the FileHeader.
    49  func (f *File) FileInfo() os.FileInfo {
    50  	return f.file.FileInfo()
    51  }
    52  
    53  // MarshalJSON implements the interface MarshalJSON for json.Marshal.
    54  func (f *File) MarshalJSON() ([]byte, error) {
    55  	info := f.FileInfo()
    56  	return json.Marshal(map[string]interface{}{
    57  		"name": f.Name(),
    58  		"size": info.Size(),
    59  		"time": info.ModTime(),
    60  		"file": !info.IsDir(),
    61  	})
    62  }