Created
August 7, 2014 17:56
-
-
Save scorphus/2cc2f181422d9f934f87 to your computer and use it in GitHub Desktop.
multipartzip.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2014 gandalf authors. All rights reserved. | |
// Use of this source code is governed by a BSD-style | |
// license that can be found in the LICENSE file. | |
package multipartzip | |
import ( | |
"archive/zip" | |
"bytes" | |
"io" | |
"log" | |
"mime/multipart" | |
"path/filepath" | |
) | |
func CreateZipBuffer(files []struct{ Name, Body string }) (*bytes.Buffer, error) { | |
buf := new(bytes.Buffer) | |
w := zip.NewWriter(buf) | |
for _, file := range files { | |
f, err := w.Create(file.Name) | |
if err != nil { | |
return nil, err | |
} | |
_, err = f.Write([]byte(file.Body)) | |
if err != nil { | |
return nil, err | |
} | |
} | |
err := w.Close() | |
if err != nil { | |
return nil, err | |
} | |
return buf, nil | |
} | |
func StreamWriteBuffer(params map[string]string, paramName, path, boundary string, writer *io.PipeWriter, buf *bytes.Buffer) { | |
defer writer.Close() | |
mpwriter := multipart.NewWriter(writer) | |
mpwriter.SetBoundary(boundary) | |
part, err := mpwriter.CreateFormFile(paramName, filepath.Base(path)) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
_, err = io.Copy(part, buf) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
for key, val := range params { | |
_ = mpwriter.WriteField(key, val) | |
} | |
err = mpwriter.Close() | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment