github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/Unknwon/cae/zip/stream.go (about)

     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  
    15  package zip
    16  
    17  import (
    18  	"archive/zip"
    19  	"io"
    20  	"os"
    21  	"path/filepath"
    22  )
    23  
    24  // A StreamArchive represents a streamable archive.
    25  type StreamArchive struct {
    26  	*zip.Writer
    27  }
    28  
    29  // NewStreamArachive returns a new streamable archive with given io.Writer.
    30  // It's caller's responsibility to close io.Writer and streamer after operation.
    31  func NewStreamArachive(w io.Writer) *StreamArchive {
    32  	return &StreamArchive{zip.NewWriter(w)}
    33  }
    34  
    35  // StreamFile streams a file or directory entry into StreamArchive.
    36  func (s *StreamArchive) StreamFile(relPath string, fi os.FileInfo, data []byte) error {
    37  	if fi.IsDir() {
    38  		fh, err := zip.FileInfoHeader(fi)
    39  		if err != nil {
    40  			return err
    41  		}
    42  		fh.Name = relPath + "/"
    43  		if _, err = s.Writer.CreateHeader(fh); err != nil {
    44  			return err
    45  		}
    46  	} else {
    47  		fh, err := zip.FileInfoHeader(fi)
    48  		if err != nil {
    49  			return err
    50  		}
    51  		fh.Name = filepath.Join(relPath, fi.Name())
    52  		fh.Method = zip.Deflate
    53  		fw, err := s.Writer.CreateHeader(fh)
    54  		if err != nil {
    55  			return err
    56  		} else if _, err = fw.Write(data); err != nil {
    57  			return err
    58  		}
    59  	}
    60  	return nil
    61  }
    62  
    63  // StreamReader streams data from io.Reader to StreamArchive.
    64  func (s *StreamArchive) StreamReader(relPath string, fi os.FileInfo, r io.Reader) (err error) {
    65  	fh, err := zip.FileInfoHeader(fi)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	fh.Name = filepath.Join(relPath, fi.Name())
    70  
    71  	fw, err := s.Writer.CreateHeader(fh)
    72  	if err != nil {
    73  		return err
    74  	}
    75  	_, err = io.Copy(fw, r)
    76  	return err
    77  }