gres_file.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2019 gf Author(https://github.com/gogf/gf). 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. package gres
  7. import (
  8. "archive/zip"
  9. "bytes"
  10. "github.com/gogf/gf/internal/json"
  11. "io"
  12. "os"
  13. )
  14. type File struct {
  15. file *zip.File
  16. reader *bytes.Reader
  17. resource *Resource
  18. }
  19. // Name returns the name of the file.
  20. func (f *File) Name() string {
  21. return f.file.Name
  22. }
  23. // Open returns a ReadCloser that provides access to the File's contents.
  24. // Multiple files may be read concurrently.
  25. func (f *File) Open() (io.ReadCloser, error) {
  26. return f.file.Open()
  27. }
  28. // Content returns the content of the file.
  29. func (f *File) Content() []byte {
  30. reader, err := f.Open()
  31. if err != nil {
  32. return nil
  33. }
  34. defer reader.Close()
  35. buffer := bytes.NewBuffer(nil)
  36. if _, err := io.Copy(buffer, reader); err != nil {
  37. return nil
  38. }
  39. return buffer.Bytes()
  40. }
  41. // FileInfo returns an os.FileInfo for the FileHeader.
  42. func (f *File) FileInfo() os.FileInfo {
  43. return f.file.FileInfo()
  44. }
  45. // MarshalJSON implements the interface MarshalJSON for json.Marshal.
  46. func (f *File) MarshalJSON() ([]byte, error) {
  47. info := f.FileInfo()
  48. return json.Marshal(map[string]interface{}{
  49. "name": f.Name(),
  50. "size": info.Size(),
  51. "time": info.ModTime(),
  52. "file": !info.IsDir(),
  53. })
  54. }