當前位置: 首頁>>代碼示例>>Golang>>正文


Golang multipart.NewWriter函數代碼示例

本文整理匯總了Golang中mime/multipart.NewWriter函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewWriter函數的具體用法?Golang NewWriter怎麽用?Golang NewWriter使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewWriter函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestMultipartMIME

func TestMultipartMIME(t *testing.T) {
	var mime bytes.Buffer
	writer := multipart.NewWriter(&mime)
	if err := multipartMIME(writer, msgs.Message1, nil); err != nil {
		t.Fatal(err)
	}
	if err := writer.Close(); err != nil {
		t.Fatal(err)
	}
	mime.Reset()
	writer = multipart.NewWriter(&mime)
	err := multipartMIME(writer, msgs.Message1,
		[]*Attachment{
			{
				Filename:    "message.txt",
				Reader:      bytes.NewBufferString(msgs.Message2),
				ContentType: "application/octet-stream",
			},
		})
	if err != nil {
		t.Fatal(err)
	}
	if err := writer.Close(); err != nil {
		t.Fatal(err)
	}
}
開發者ID:JonathanLogan,項目名稱:mute,代碼行數:26,代碼來源:mime_test.go

示例2: TestUntypedFileUpload

func TestUntypedFileUpload(t *testing.T) {
	binder := paramsForFileUpload()

	body := bytes.NewBuffer(nil)
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile("file", "plain-jane.txt")
	assert.NoError(t, err)

	part.Write([]byte("the file contents"))
	writer.WriteField("name", "the-name")
	assert.NoError(t, writer.Close())

	urlStr := "http://localhost:8002/hello"
	req, _ := http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	data := make(map[string]interface{})
	assert.NoError(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
	assert.Equal(t, "the-name", data["name"])
	assert.NotNil(t, data["file"])
	assert.IsType(t, httpkit.File{}, data["file"])
	file := data["file"].(httpkit.File)
	assert.NotNil(t, file.Header)
	assert.Equal(t, "plain-jane.txt", file.Header.Filename)

	bb, err := ioutil.ReadAll(file.Data)
	assert.NoError(t, err)
	assert.Equal(t, []byte("the file contents"), bb)

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", "application/json")
	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", "application(")
	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	body = bytes.NewBuffer(nil)
	writer = multipart.NewWriter(body)
	part, err = writer.CreateFormFile("bad-name", "plain-jane.txt")
	assert.NoError(t, err)

	part.Write([]byte("the file contents"))
	writer.WriteField("name", "the-name")
	assert.NoError(t, writer.Close())
	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))

	req, _ = http.NewRequest("POST", urlStr, body)
	req.Header.Set("Content-Type", writer.FormDataContentType())
	req.MultipartReader()

	data = make(map[string]interface{})
	assert.Error(t, binder.Bind(req, nil, httpkit.JSONConsumer(), &data))
}
開發者ID:ericchiang,項目名稱:go-swagger,代碼行數:60,代碼來源:untyped_request_test.go

示例3: ConditionallyIncludeMedia

// ConditionallyIncludeMedia does nothing if media is nil.
//
// bodyp is an in/out parameter.  It should initially point to the
// reader of the application/json (or whatever) payload to send in the
// API request.  It's updated to point to the multipart body reader.
//
// ctypep is an in/out parameter.  It should initially point to the
// content type of the bodyp, usually "application/json".  It's updated
// to the "multipart/related" content type, with random boundary.
//
// The return value is the content-length of the entire multpart body.
func ConditionallyIncludeMedia(media io.Reader, bodyp *io.Reader, ctypep *string) (totalContentLength int64, ok bool) {
	if media == nil {
		return
	}
	// Get the media type and size. The type check might return a
	// different reader instance, so do the size check first,
	// which looks at the specific type of the io.Reader.
	var mediaType string
	if typer, ok := media.(ContentTyper); ok {
		mediaType = typer.ContentType()
	}
	media, mediaSize := getReaderSize(media)
	if mediaType == "" {
		media, mediaType = getMediaType(media)
	}
	body, bodyType := *bodyp, *ctypep
	body, bodySize := getReaderSize(body)

	// Calculate how big the the multipart will be.
	{
		totalContentLength = bodySize + mediaSize
		mpw := multipart.NewWriter(countingWriter{&totalContentLength})
		mpw.CreatePart(typeHeader(bodyType))
		mpw.CreatePart(typeHeader(mediaType))
		mpw.Close()
	}

	pr, pw := io.Pipe()
	mpw := multipart.NewWriter(pw)
	*bodyp = pr
	*ctypep = "multipart/related; boundary=" + mpw.Boundary()
	go func() {
		defer pw.Close()
		defer mpw.Close()

		w, err := mpw.CreatePart(typeHeader(bodyType))
		if err != nil {
			return
		}
		_, err = io.Copy(w, body)
		if err != nil {
			return
		}

		w, err = mpw.CreatePart(typeHeader(mediaType))
		if err != nil {
			return
		}
		_, err = io.Copy(w, media)
		if err != nil {
			return
		}
	}()
	return totalContentLength, true
}
開發者ID:vanloswang,項目名稱:flannel,代碼行數:66,代碼來源:googleapi.go

示例4: Bytes

// Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
func (m *Message) Bytes() ([]byte, error) {
	// TODO: better guess buffer size
	buff := bytes.NewBuffer(make([]byte, 0, 4096))

	headers := m.msgHeaders()
	w := multipart.NewWriter(buff)
	// TODO: determine the content type based on message/attachment mix.
	headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
	headerToBytes(buff, headers)
	io.WriteString(buff, "\r\n")

	// Start the multipart/mixed part
	fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
	header := textproto.MIMEHeader{}
	// Check to see if there is a Text or HTML field
	if len(m.Content) > 0 {
		subWriter := multipart.NewWriter(buff)
		// Create the multipart alternative part
		header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
		// Write the header
		headerToBytes(buff, header)
		// Create the body sections
		if len(m.Content) > 0 {
			header.Set("Content-Type", fmt.Sprintf("%s; charset=UTF-8", m.ContentType))
			header.Set("Content-Transfer-Encoding", "quoted-printable")
			if _, err := subWriter.CreatePart(header); err != nil {
				return nil, err
			}
			// Write the text
			if err := quotePrintEncode(buff, []byte(m.Content)); err != nil {
				return nil, err
			}
		}

		if err := subWriter.Close(); err != nil {
			return nil, err
		}
	}
	// Create attachment part, if necessary
	for _, a := range m.Attachments {
		ap, err := w.CreatePart(a.Header)
		if err != nil {
			return nil, err
		}
		// Write the base64Wrapped content to the part
		base64Wrap(ap, a.Content)
	}
	if err := w.Close(); err != nil {
		return nil, err
	}
	return buff.Bytes(), nil
}
開發者ID:nanjishidu,項目名稱:going,代碼行數:53,代碼來源:messge.go

示例5: NewFileUploadRequest

func NewFileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, file)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	writer.WriteField("type", "video/mp4")

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

	req, err := http.NewRequest("POST", uri, body)
	if err == nil {
		req.Header.Add("Content-Type", writer.FormDataContentType())
	}

	return req, err
}
開發者ID:yukidarake,項目名稱:isucon4,代碼行數:32,代碼來源:util.go

示例6: streamingUploadFile

// Streams upload directly from file -> mime/multipart -> pipe -> http-request
func streamingUploadFile(params map[string]string, paramName, path string, w *io.PipeWriter, file *os.File) {
	defer file.Close()
	defer w.Close()
	writer := multipart.NewWriter(w)
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		log.Fatal(err)
		return
	}
	_, err = io.Copy(part, file)
	if err != nil {
		log.Fatal(err)
		return
	}

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}

	err = writer.Close()
	if err != nil {
		log.Fatal(err)
		return
	}
}
開發者ID:mickelsonm,項目名稱:go-fileupload-example,代碼行數:26,代碼來源:main.go

示例7: buildFormFileReq

func buildFormFileReq(t *testing.T, tc *fileTestCase) *http.Request {
	var b bytes.Buffer
	w := multipart.NewWriter(&b)

	w.WriteField("title", tc.title)
	for _, doc := range tc.documents {
		fw, err := w.CreateFormFile("document", doc.fileName)
		if err != nil {
			t.Error(err)
		}
		fw.Write([]byte(doc.data))
	}

	err := w.Close()
	if err != nil {
		t.Error(err)
	}

	req, err := http.NewRequest("POST", filepath, &b)
	if err != nil {
		t.Error(err)
	}

	req.Header.Set("Content-Type", w.FormDataContentType())
	return req
}
開發者ID:joshk,項目名稱:hustle,代碼行數:26,代碼來源:binding_test.go

示例8: NewMultipartWriter

func NewMultipartWriter() *MultipartWriter {
	buf := &bytes.Buffer{}
	return &MultipartWriter{
		Buffer: buf,
		Writer: multipart.NewWriter(buf),
	}
}
開發者ID:marsmensch,項目名稱:blobstash,代碼行數:7,代碼來源:client.go

示例9: getHandler

// The getHandler function handles the GET endpoint for the artifact path.
// It calls the RetrieveArtifact function, and then either returns the found artifact, or logs the error
// returned by RetrieveArtifact.
func (s *httpServer) getHandler(w http.ResponseWriter, r *http.Request) {
	log.Debug("GET %s", r.URL.Path)
	artifactPath := strings.TrimPrefix(r.URL.Path, "/artifact/")

	art, err := s.cache.RetrieveArtifact(artifactPath)
	if err != nil && os.IsNotExist(err) {
		w.WriteHeader(http.StatusNotFound)
		log.Debug("%s doesn't exist in http cache", artifactPath)
		return
	} else if err != nil {
		log.Errorf("Failed to retrieve artifact %s: %s", artifactPath, err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// In order to handle directories we use multipart encoding.
	// Note that we don't bother on the upload because the client knows all the parts and can
	// send individually; here they don't know what they'll need to expect.
	// We could use it for upload too which might be faster and would be more symmetric, but
	// multipart is a bit fiddly so for now we're not bothering.
	mw := multipart.NewWriter(w)
	defer mw.Close()
	w.Header().Set("Content-Type", mw.FormDataContentType())
	for name, body := range art {
		if part, err := mw.CreateFormFile(name, name); err != nil {
			log.Errorf("Failed to create form file %s: %s", name, err)
			w.WriteHeader(http.StatusInternalServerError)
		} else if _, err := io.Copy(part, bytes.NewReader(body)); err != nil {
			log.Errorf("Failed to write form file %s: %s", name, err)
			w.WriteHeader(http.StatusInternalServerError)
		}
	}
}
開發者ID:thought-machine,項目名稱:please,代碼行數:36,代碼來源:http_server.go

示例10: PostFile

// PostFile issues a POST to the fcgi responder in multipart(RFC 2046) standard,
// with form as a string key to a list values (url.Values),
// and/or with file as a string key to a list file path.
func (this *FCGIClient) PostFile(p map[string]string, data url.Values, file map[string]string) (resp *http.Response, err error) {
	buf := &bytes.Buffer{}
	writer := multipart.NewWriter(buf)
	bodyType := writer.FormDataContentType()

	for key, val := range data {
		for _, v0 := range val {
			err = writer.WriteField(key, v0)
			if err != nil {
				return
			}
		}
	}

	for key, val := range file {
		fd, e := os.Open(val)
		if e != nil {
			return nil, e
		}
		defer fd.Close()

		part, e := writer.CreateFormFile(key, filepath.Base(val))
		if e != nil {
			return nil, e
		}
		_, err = io.Copy(part, fd)
	}

	err = writer.Close()
	if err != nil {
		return
	}

	return this.Post(p, bodyType, buf, buf.Len())
}
開發者ID:andviro,項目名稱:fcgi_client,代碼行數:38,代碼來源:fcgiclient.go

示例11: main

func main() {

	// http Listener
	go func() {
		http.HandleFunc("/", handler)
		http.ListenAndServe(":9999", nil)
	}()

	// build multipart request
	buf := bytes.Buffer{}
	multipartWriter := multipart.NewWriter(&buf)
	multipartWriter.WriteField("foo", "bar")
	multipartWriter.WriteField("hoge", "fuga")
	multipartWriter.Close()

	// request body
	fmt.Println("# Request Body")
	fmt.Println(buf.String())

	req, err := http.NewRequest("POST", "http://localhost:9999/", &buf)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	req.Header.Add("Content-Type", multipartWriter.FormDataContentType())

	// request
	client := &http.Client{}
	_, err = client.Do(req)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
開發者ID:shohhei1126,項目名稱:go,代碼行數:34,代碼來源:multipart.go

示例12: StreamWriteMultipartForm

func StreamWriteMultipartForm(params map[string]string, fileField, path, boundary string, pw *io.PipeWriter, buf *bytes.Buffer) {
	defer pw.Close()
	mpw := multipart.NewWriter(pw)
	mpw.SetBoundary(boundary)
	if fileField != "" && path != "" {
		fw, err := mpw.CreateFormFile(fileField, filepath.Base(path))
		if err != nil {
			log.Fatal(err)
			return
		}
		if buf != nil {
			_, err = io.Copy(fw, buf)
			if err != nil {
				log.Fatal(err)
				return
			}
		}
	}
	for key, val := range params {
		_ = mpw.WriteField(key, val)
	}
	err := mpw.Close()
	if err != nil {
		log.Fatal(err)
		return
	}
}
開發者ID:rfloriano,項目名稱:gandalf,代碼行數:27,代碼來源:mocks.go

示例13: newfileUploadRequest

// based on https://gist.githubusercontent.com/mattetti/5914158/raw/51ee58b51c43f797f200d273853f64e13aa21a8a/multipart_upload.go
func (t *Client) newfileUploadRequest(uri string, params map[string]string, bodyField string, toUpload []byte) (*http.Request, error) {
	glog.V(0).Infoln("newfileUploadRequest", uri)
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	p, err := writer.CreateFormField(bodyField)

	if err != nil {
		return nil, t.Finalize("can't create form field", err)
	}

	_, err = p.Write(toUpload)
	if err != nil {
		return nil, t.Finalize("can't write payload", err)
	}
	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, t.Finalize("close failed", err)
	}

	req, err := http.NewRequest("POST", uri, body)
	if err != nil {
		return nil, t.Finalize("new request failed", err)
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())
	return req, nil
}
開發者ID:ibm-security-innovation,項目名稱:menagerie,代碼行數:30,代碼來源:menagerie_client.go

示例14: createFileParam

func createFileParam(param, path string) (*bytes.Buffer, string, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	defer writer.Close()

	p, err := filepath.Abs(path)
	if err != nil {
		return nil, "", err
	}
	file, err := os.Open(p)
	if err != nil {
		return nil, "", err
	}
	defer file.Close()
	part, err := writer.CreateFormFile(param, filepath.Base(path))
	if err != nil {
		return nil, "", err
	}

	_, err = io.Copy(part, file)
	if err != nil {
		return nil, "", err
	}

	return body, writer.FormDataContentType(), nil
}
開發者ID:plutov,項目名稱:slack,代碼行數:26,代碼來源:files.go

示例15: ChannelFileSend

// ChannelFileSend sends a file to the given channel.
// channelID : The ID of a Channel.
// io.Reader : A reader for the file contents.
func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {

	body := &bytes.Buffer{}
	bodywriter := multipart.NewWriter(body)

	writer, err := bodywriter.CreateFormFile("file", name)
	if err != nil {
		return nil, err
	}

	_, err = io.Copy(writer, r)
	if err != nil {
		return
	}

	err = bodywriter.Close()
	if err != nil {
		return
	}

	response, err := s.request("POST", EndpointChannelMessages(channelID), bodywriter.FormDataContentType(), body.Bytes())
	if err != nil {
		return
	}

	err = unmarshal(response, &st)
	return
}
開發者ID:42wim,項目名稱:matterbridge,代碼行數:31,代碼來源:restapi.go


注:本文中的mime/multipart.NewWriter函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。