stream.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2014 Unknown
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package zip
  15. import (
  16. "archive/zip"
  17. "io"
  18. "os"
  19. "path/filepath"
  20. )
  21. // A StreamArchive represents a streamable archive.
  22. type StreamArchive struct {
  23. *zip.Writer
  24. }
  25. // NewStreamArachive returns a new streamable archive with given io.Writer.
  26. // It's caller's responsibility to close io.Writer and streamer after operation.
  27. func NewStreamArachive(w io.Writer) *StreamArchive {
  28. return &StreamArchive{zip.NewWriter(w)}
  29. }
  30. // StreamFile streams a file or directory entry into StreamArchive.
  31. func (s *StreamArchive) StreamFile(relPath string, fi os.FileInfo, data []byte) error {
  32. if fi.IsDir() {
  33. fh, err := zip.FileInfoHeader(fi)
  34. if err != nil {
  35. return err
  36. }
  37. fh.Name = relPath + "/"
  38. if _, err = s.Writer.CreateHeader(fh); err != nil {
  39. return err
  40. }
  41. } else {
  42. fh, err := zip.FileInfoHeader(fi)
  43. if err != nil {
  44. return err
  45. }
  46. fh.Name = filepath.Join(relPath, fi.Name())
  47. fh.Method = zip.Deflate
  48. fw, err := s.Writer.CreateHeader(fh)
  49. if err != nil {
  50. return err
  51. } else if _, err = fw.Write(data); err != nil {
  52. return err
  53. }
  54. }
  55. return nil
  56. }
  57. // StreamReader streams data from io.Reader to StreamArchive.
  58. func (s *StreamArchive) StreamReader(relPath string, fi os.FileInfo, r io.Reader) (err error) {
  59. fh, err := zip.FileInfoHeader(fi)
  60. if err != nil {
  61. return err
  62. }
  63. fh.Name = filepath.Join(relPath, fi.Name())
  64. fw, err := s.Writer.CreateHeader(fh)
  65. if err != nil {
  66. return err
  67. }
  68. _, err = io.Copy(fw, r)
  69. return err
  70. }