Golang archive-zip.NewWriter类(方法)实例源码

下面列出了Golang archive-zip.NewWriter 类(方法)源码代码实例,从而了解它的用法。

作者:cgrate    项目:cgrate   
func NewTPExporter(storDb LoadStorage, tpID, expPath, fileFormat, sep string, compress bool) (*TPExporter, error) {
	if len(tpID) == 0 {
		return nil, errors.New("Missing TPid")
	}
	if !utils.IsSliceMember(TPExportFormats, fileFormat) {
		return nil, errors.New("Unsupported file format")
	}
	tpExp := &TPExporter{
		storDb:     storDb,
		tpID:       tpID,
		exportPath: expPath,
		fileFormat: fileFormat,
		compress:   compress,
		cacheBuff:  new(bytes.Buffer),
	}
	runeSep, _ := utf8.DecodeRuneInString(sep)
	if runeSep == utf8.RuneError {
		return nil, fmt.Errorf("Invalid field separator: %s", sep)
	} else {
		tpExp.sep = runeSep
	}
	if compress {
		if len(tpExp.exportPath) == 0 {
			tpExp.zipWritter = zip.NewWriter(tpExp.cacheBuff)
		} else {
			if fileOut, err := os.Create(path.Join(tpExp.exportPath, "tpexport.zip")); err != nil {
				return nil, err
			} else {
				tpExp.zipWritter = zip.NewWriter(fileOut)
			}
		}
	}
	return tpExp, nil
}

作者:Graylog    项目:apoll   
func zipIt(files []IncludedFile) string {
	buf := new(bytes.Buffer)
	zipWriter := zip.NewWriter(buf)

	for _, file := range files {
		zipFile, err := zipWriter.Create(file.Name)
		if err != nil {
			check(err)
		}
		_, err = zipFile.Write([]byte(file.Body))
		if err != nil {
			check(err)
		}
	}

	err := zipWriter.Close()
	check(err)

	// Write zipfile to disk.
	t := time.Now()
	finalName := fmt.Sprintf("graylog_apollo_bundle-%d-%02d-%02dT%02d-%02d-%02d.zip", t.Year(), t.Month(), t.Day(),
		t.Hour(), t.Minute(), t.Second())
	ioutil.WriteFile(finalName, buf.Bytes(), 0644)

	return finalName
}

作者:rodney-vi    项目:cl   
func writeZipFile(dir string, targetFile *os.File) (err error) {
	isEmpty, err := fileutils.IsDirEmpty(dir)
	if err != nil {
		return
	}
	if isEmpty {
		err = errors.New("Directory is empty")
		return
	}

	writer := zip.NewWriter(targetFile)
	defer writer.Close()

	err = WalkAppFiles(dir, func(fileName string, fullPath string) (err error) {
		fileInfo, err := os.Stat(fullPath)
		if err != nil {
			return err
		}

		header, err := zip.FileInfoHeader(fileInfo)
		header.Name = filepath.ToSlash(fileName)
		if err != nil {
			return err
		}

		zipFilePart, err := writer.CreateHeader(header)
		err = fileutils.CopyPathToWriter(fullPath, zipFilePart)
		return
	})

	return
}

作者:Chander    项目:docke   
// ExportKeysByGUN exports all keys associated with a specified GUN to an
// io.Writer in zip format. passphraseRetriever is used to select new passphrases to use to
// encrypt the keys.
func (km *KeyStoreManager) ExportKeysByGUN(dest io.Writer, gun string, passphraseRetriever passphrase.Retriever) error {
	tempBaseDir, err := ioutil.TempDir("", "notary-key-export-")
	defer os.RemoveAll(tempBaseDir)

	privNonRootKeysSubdir := filepath.Join(privDir, nonRootKeysSubdir)

	// Create temporary keystore to use as a staging area
	tempNonRootKeysPath := filepath.Join(tempBaseDir, privNonRootKeysSubdir)
	tempNonRootKeyStore, err := trustmanager.NewKeyFileStore(tempNonRootKeysPath, passphraseRetriever)
	if err != nil {
		return err
	}

	if err := moveKeysByGUN(km.nonRootKeyStore, tempNonRootKeyStore, gun); err != nil {
		return err
	}

	zipWriter := zip.NewWriter(dest)

	if len(tempNonRootKeyStore.ListKeys()) == 0 {
		return ErrNoKeysFoundForGUN
	}

	if err := addKeysToArchive(zipWriter, tempNonRootKeyStore, privNonRootKeysSubdir); err != nil {
		return err
	}

	zipWriter.Close()

	return nil
}

作者:dsipasseut    项目:forc   
// Just zip up what ever is in the path
func zipResource(path string, topLevelFolder string) {
	zipfile := new(bytes.Buffer)
	zipper := zip.NewWriter(zipfile)
	startPath := path + "/"
	filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
		if filepath.Base(path) != ".DS_Store" {
			// Can skip dirs since the dirs will be created when the files are added
			if !f.IsDir() {
				file, err := ioutil.ReadFile(path)
				if err != nil {
					return err
				}
				fl, err := zipper.Create(filepath.Join(topLevelFolder, strings.Replace(path, startPath, "", -1)))
				if err != nil {
					ErrorAndExit(err.Error())
				}
				_, err = fl.Write([]byte(file))
				if err != nil {
					ErrorAndExit(err.Error())
				}
			}
		}
		return nil
	})

	zipper.Close()
	zipdata := zipfile.Bytes()
	ioutil.WriteFile(path+".resource", zipdata, 0644)
	return
}

作者:enderl    项目:vf   
func ExampleWriter() {
	// Create a buffer to write our archive to.
	buf := new(bytes.Buffer)

	// Create a new zip archive.
	w := zip.NewWriter(buf)

	// Add some files to the archive.
	var files = []struct {
		Name, Body string
	}{
		{"readme.txt", "This archive contains some text files."},
		{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
		{"todo.txt", "Get animal handling licence.\nWrite more examples."},
	}
	for _, file := range files {
		f, err := w.Create(file.Name)
		if err != nil {
			log.Fatal(err)
		}
		_, err = f.Write([]byte(file.Body))
		if err != nil {
			log.Fatal(err)
		}
	}

	// Make sure to check the error on Close.
	err := w.Close()
	Strtofile(buf.Bytes(), `c:\xx.zip`)
	if err != nil {
		log.Fatal(err)
	}
}

作者:krabke    项目:xls   
// Save the File to an xlsx file at the provided path.
func (f *File) Save(path string) (err error) {
	var parts map[string]string
	var target *os.File
	var zipWriter *zip.Writer

	parts, err = f.MarshallParts()
	if err != nil {
		return
	}

	target, err = os.Create(path)
	if err != nil {
		return
	}

	zipWriter = zip.NewWriter(target)

	for partName, part := range parts {
		var writer io.Writer
		writer, err = zipWriter.Create(partName)
		if err != nil {
			return
		}
		_, err = writer.Write([]byte(part))
		if err != nil {
			return
		}
	}
	err = zipWriter.Close()
	if err != nil {
		return
	}

	return target.Close()
}

作者:uka    项目:go-programming-blueprint   
func (z *zipper) Archive(src, dest string) error {
	if err := os.MkdirAll(filepath.Dir(dest), 0777); err != nil {
		return err
	}
	out, err := os.Create(dest)
	if err != nil {
		return err
	}
	defer out.Close()
	w := zip.NewWriter(out)
	defer w.Close()
	return filepath.Walk(src, func(path string, info os.FileInfo,
		err error) error {
		if info.IsDir() {
			return nil // スキップします
		}
		if err != nil {
			return err
		}
		in, err := os.Open(path)
		if err != nil {
			return err
		}
		defer in.Close()
		f, err := w.Create(path)
		if err != nil {
			return err
		}
		io.Copy(f, in)
		return nil
	})
}

作者:elegio    项目:Scrib   
func getZip(e env, projectId string) bool {
	userKey, done := getUser(e)
	if done {
		return true
	}

	snapshot, snapshotKey, done := getLastSnapshot(e, userKey, projectId)
	if done {
		return true
	}

	e.w.Header().Set("Content-Type", "application/zip")
	e.w.Header().Set("Content-Disposition", "inline; filename="+projectId+".zip")

	w := zip.NewWriter(e.w)
	done = addZipFile(e, w, "", snapshot.Top, snapshotKey)
	if done {
		return true
	}

	err := w.Close()
	if err != nil {
		e.w.Header().Set("Content-type", "text/html; charset=utf-8")
		e.w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(e.w, `Could not wrap up the zip file`)
		log.Println("Error finishing zip file", err)
		return true
	}

	return true
}

作者:erikserran    项目:compres   
// Función encargada de crear un archivo ZIP y escribir sobre él el contenido
// de un directorio/archivo
func Zip(startPath, finalFileName, finalFilePath string) error {
	// Abrimos la ruta inicial
	startDirectory, err := openPath(startPath)
	if err != nil {
		return err
	}
	// Cerramos la ruta inicial
	defer startDirectory.Close()

	// Creamos directorio destino
	if err := createDirectory(finalFilePath, 0777); err != nil {
		return err
	}

	// Creamos archivo ZIP
	zipFile, err := createFile(finalFilePath + finalFileName)
	if err != nil {
		return err
	}
	// Cerramos archivo ZIP
	defer zipFile.Close()

	// Creamos writer para el archivo ZIP
	zipWriter := zip.NewWriter(zipFile)
	// Cerramos Writer
	defer zipWriter.Close()

	// Iniciamos recorrido del directorio
	if err := walkDirectory(startDirectory, zipWriter); err != nil {
		return err
	}
	return nil
}

作者:anansi    项目:docx-template   
// WriteToFile creates a zip with all its contents
func (d *Docx) WriteToFile(target string) error {
	docxFile, err := os.Create(target)
	if err != nil {
		return err
	}
	defer docxFile.Close()

	d.Writer = zip.NewWriter(docxFile)
	defer d.Writer.Close()

	for _, f := range d.Files {
		zippedFile, err := d.Writer.Create(f.Name)
		if err != nil {
			return err
		}
		zippedFile.Write(f.Contents)
	}

	zippedFile, err := d.Writer.Create("word/document.xml")
	if err != nil {
		return err
	}
	zippedFile.Write([]byte(d.WordXML))

	return nil
}

作者:JustinJud    项目:golang-n   
func nwBuild(nw string) error {
	w, err := os.Create(nw)
	if err != nil {
		return err
	}
	defer w.Close()

	zw := zip.NewWriter(w)
	defer zw.Close()

	r, err := os.Open(app)
	if err != nil {
		return err
	}
	defer r.Close()

	bin := filepath.Base(app)
	p := build.Package{Name: name, Bin: bin, Window: build.Window{Title: name, Toolbar: toolbar, Fullscreen: fullscreen, Frame: frame}}

	if err := p.CreateNW(zw, build.DefaultTemplates, r, includesDir); err != nil {
		return err
	}

	return nil
}

作者:cwlbra    项目:cf-acceptance-test   
func CreateZipArchive(filename string, files []ArchiveFile) {
	file, err := os.Create(filename)
	Ω(err).ShouldNot(HaveOccurred())

	w := zip.NewWriter(file)

	for _, file := range files {
		header := &zip.FileHeader{
			Name: file.Name,
		}

		mode := file.Mode
		if mode == 0 {
			mode = 0777
		}

		header.SetMode(os.FileMode(mode))

		f, err := w.CreateHeader(header)
		Ω(err).ShouldNot(HaveOccurred())

		_, err = f.Write([]byte(file.Body))
		Ω(err).ShouldNot(HaveOccurred())
	}

	err = w.Close()
	Ω(err).ShouldNot(HaveOccurred())

	err = file.Close()
	Ω(err).ShouldNot(HaveOccurred())
}

作者:cookieo    项目:resources-g   
func CreateTestZip(t *T) *bytes.Reader {
	t.Log("Creating in-memory zip file")
	buf := new(bytes.Buffer)
	zw := zip.NewWriter(buf)
	for _, file := range files {
		t.Logf("Adding file %q (%d bytes) to zip file", file.Path, len(file.Contents))

		fw, err := zw.Create(file.Path)
		if err != nil {
			t.Fatal(err)
		}
		if _, err := fw.Write(file.Contents); err != nil {
			t.Fatal(err)
		}
	}

	t.Logf("Creating Manifest in zip file")
	if fw, err := zw.Create("MANIFEST"); err != nil {
		t.Fatal(err)
	} else {
		for _, file := range files {
			mimestring := http.DetectContentType(file.Contents)
			mediatype, params, err := mime.ParseMediaType(mimestring)
			if err != nil {
				t.Fatal(err)
			}
			fmt.Fprintf(fw, "%s (%d bytes): %s %v\n", file.Path, len(file.Contents), mediatype, params)
		}
	}
	if err := zw.Close(); err != nil {
		t.Fatal(err)
	}
	t.Log("Finished zip file,", buf.Len(), "bytes written.")
	return bytes.NewReader(buf.Bytes())
}

作者:kuba-    项目:c-go-zi   
//export Zip
func Zip(zipname *C.char, filenames []*C.char) int32 {
	f, err := os.Create(C.GoString(zipname))
	if err != nil {
		log.Println(err)
		return -1
	}
	defer f.Close()

	w := zip.NewWriter(f)
	defer w.Close()

	for _, name := range filenames {
		ww, err := w.Create(C.GoString(name))
		if err != nil {
			log.Println(err)
			return -1
		}

		fi, err := os.Open(C.GoString(name))
		if err != nil {
			log.Println(err)
			return -1
		}
		defer fi.Close()

		if _, err := io.Copy(ww, fi); err != nil {
			log.Println(err)
			return -1
		}
	}

	return 0
}

作者:robertkrime    项目:dogba   
func _zipbagWalk(input string) (*bytes.Buffer, error) {
	archive := &bytes.Buffer{}
	zipWriter := zip.NewWriter(archive)

	if input != "" {
		err := walk("", input, zipWriter)
		if err != nil {
			return nil, err
		}
	}

	err := zipWriter.Close()
	if err != nil {
		return nil, err
	}

	var data bytes.Buffer
	encoder := &byteWriter{Writer: &data}
	_, err = io.Copy(encoder, archive)
	if err != nil {
		return nil, err
	}

	return &data, nil
}

作者:icsnj    项目:apt-cor   
// zip file
func Zipit(source, target string) error {
	zipfile, err := os.Create(target)
	if err != nil {
		return err
	}
	defer zipfile.Close()

	archive := zip.NewWriter(zipfile)
	defer archive.Close()

	info, err := os.Stat(source)
	if err != nil {
		return nil
	}

	var baseDir string
	if info.IsDir() {
		baseDir = filepath.Base(source)
	}

	filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}

		if baseDir != "" {
			header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
		}

		if info.IsDir() {
			header.Name += "/"
		} else {
			header.Method = zip.Deflate
		}

		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		file, err := os.Open(path)
		if err != nil {
			return err
		}
		defer file.Close()
		_, err = io.Copy(writer, file)
		return err
	})

	return err
}

作者:useide    项目:notar   
// Zips up the keys in the old repo, and assert that we can import it and use
// said keys.  The 0.1 exported format is just a zip file of all the keys
func TestImport0Dot1Zip(t *testing.T) {
	ks, ret, gun := get0Dot1(t)

	zipFile, err := ioutil.TempFile("", "notary-test-zipFile")
	defer os.RemoveAll(zipFile.Name())
	zipWriter := zip.NewWriter(zipFile)
	assert.NoError(t, err)
	assert.NoError(t, addKeysToArchive(zipWriter, ks))
	zipWriter.Close()
	zipFile.Close()

	origKeys := ks.ListKeys()
	assert.Len(t, origKeys, 3)

	// now import the zip file into a new cryptoservice

	tempDir, err := ioutil.TempDir("", "notary-test-import")
	defer os.RemoveAll(tempDir)
	assert.NoError(t, err)

	ks, err = trustmanager.NewKeyFileStore(tempDir, ret)
	assert.NoError(t, err)
	cs := NewCryptoService(gun, ks)

	zipReader, err := zip.OpenReader(zipFile.Name())
	assert.NoError(t, err)
	defer zipReader.Close()

	assert.NoError(t, cs.ImportKeysZip(zipReader.Reader))
	assertHasKeys(t, cs, origKeys)
}

作者:jameine    项目:cor   
// BundleTo creates a charm file from the charm expanded in dir.
// By convention a charm bundle should have a ".charm" suffix.
func (dir *Dir) BundleTo(w io.Writer) (err error) {
	zipw := zip.NewWriter(w)
	defer zipw.Close()
	zp := zipPacker{zipw, dir.Path, dir.Meta().Hooks()}
	zp.AddRevision(dir.revision)
	return filepath.Walk(dir.Path, zp.WalkFunc())
}

作者:thanze    项目:agostl   
func saveOpeners(fn string, openers []opener) (err error) {
	fh, err := os.Create(fn)
	if err != nil {
		return fmt.Errorf("Create %q: %v", fn, err)
	}
	defer func() {
		if e := fh.Close(); e != nil && err == nil {
			err = fmt.Errorf("Close %q: %v", fh.Name(), e)
		}
	}()
	zw := zip.NewWriter(fh)
	for i, o := range openers {
		src, err := o.Open()
		if err != nil {
			return fmt.Errorf("Open %s: %v", o, err)
		}
		zn := fmt.Sprintf("%03d.png", i)
		w, err := zw.Create(zn)
		if err != nil {
			_ = src.Close()
			return fmt.Errorf("Create %q: %v", zn, err)
		}
		_, err = io.Copy(w, src)
		_ = src.Close()
		if err != nil {
			return fmt.Errorf("Close %q: %v", zn, err)
		}
	}
	if err = zw.Close(); err != nil {
		return fmt.Errorf("Close %v: %v", zw, err)
	}
	return nil
}


问题


面经


文章

微信
公众号

扫码关注公众号