Example #1
0
func Zip(unBytes []byte, contentEncoding string) (zipBytes []byte, err error) {

	switch contentEncoding {
	case "":
		zipBytes = unBytes
		break

	case "gzip":
		var bf bytes.Buffer
		gw := gzip.NewWriter(&bf)
		gw.Write(unBytes)
		gw.Close()

		zipBytes = bf.Bytes()

	case "deflate":
		var bf bytes.Buffer
		var gw *flate.Writer
		gw, err = flate.NewWriter(&bf, -1)
		if err != nil {
			return
		}
		gw.Write(unBytes)
		gw.Close()

		zipBytes = bf.Bytes()

	default:
		err = fmt.Errorf("Zip Unkown Content-Encoding: %v", contentEncoding)
	}

	return
}
Example #2
0
func (self *FlateCompressor) Compress(src []byte) ([]byte, error) {
	var err error
	var compressor *flate.Writer
	cdest := bytes.NewBuffer(make([]byte, 0, len(src)))
	if self.dict == nil {
		compressor, err = flate.NewWriter(cdest, self.level)
	} else {
		compressor, err = flate.NewWriterDict(cdest, self.level, self.dict)
	}
	//compressor.Reset(cdest)
	compressor.Write(src)
	err = compressor.Close()
	if err != nil {
		fmt.Println("Compress Close err:%s", err.Error())
	}
	return cdest.Bytes(), err
}
Example #3
0
func readFile(filePath string) (string, error) {
	var buf []byte
	var err error
	var n int
	var writer *flate.Writer
	var encoder io.WriteCloser
	var file *os.File
	var data *bytes.Buffer = new(bytes.Buffer)

	if file, err = os.Open(filePath); err != nil {
		return "", err
	}
	defer file.Close()

	encoder = ascii85.NewEncoder(data)
	defer encoder.Close()

	writer, err = flate.NewWriter(encoder, flate.BestCompression)
	defer writer.Close()

	buf = make([]byte, 8192)
	err = nil
	for {
		if n, err = file.Read(buf); err != nil {
			if err == io.EOF {
				break
			} else {
				return "", err
			}
		}

		if n == 8192 {
			_, err = writer.Write(buf)
		} else {
			_, err = writer.Write(buf[:n])
		}
		if err != nil {
			return "", err
		}
	}
	if err = writer.Flush(); err != nil {
		return "", err
	}

	return strconv.Quote(string(data.Bytes())), nil
}
Example #4
0
func (e *Engine) deflate() error {
	var buf bytes.Buffer
	var level int
	var err error
	level, err = e.stack.PopInt()
	if err == nil {
		var w *flate.Writer
		w, err = flate.NewWriter(&buf, level)
		if err == nil {
			_, err = w.Write(e.stack.Pop())
			w.Close()
		}
	}
	if err == nil {
		e.stack.Push(buf.Bytes())
	}
	return err
}