本文整理汇总了Golang中mime/multipart.Writer.WriteField方法的典型用法代码示例。如果您正苦于以下问题:Golang Writer.WriteField方法的具体用法?Golang Writer.WriteField怎么用?Golang Writer.WriteField使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mime/multipart.Writer
的用法示例。
在下文中一共展示了Writer.WriteField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: sendSnapFile
func sendSnapFile(snapPath string, snapFile *os.File, pw *io.PipeWriter, mw *multipart.Writer, action *actionData) {
defer snapFile.Close()
if action.SnapOptions == nil {
action.SnapOptions = &SnapOptions{}
}
errs := []error{
mw.WriteField("action", action.Action),
mw.WriteField("name", action.Name),
mw.WriteField("snap-path", action.SnapPath),
mw.WriteField("channel", action.Channel),
mw.WriteField("devmode", strconv.FormatBool(action.DevMode)),
}
for _, err := range errs {
if err != nil {
pw.CloseWithError(err)
return
}
}
fw, err := mw.CreateFormFile("snap", filepath.Base(snapPath))
if err != nil {
pw.CloseWithError(err)
return
}
_, err = io.Copy(fw, snapFile)
if err != nil {
pw.CloseWithError(err)
return
}
mw.Close()
pw.Close()
}
示例2: Write
func Write(w *multipart.Writer, params map[string][]string) error {
for key, param1 := range params {
param := param1[0]
if len(param) > 0 && param[0] == '@' {
file := param[1:]
fw, err := w.CreateFormFile(key, file)
if err != nil {
log.Println("CreateFormFile failed:", err)
return err
}
fd, err := os.Open(file)
if err != nil {
log.Println("Open file failed:", err)
return err
} else {
_, err = io.Copy(fw, fd)
fd.Close()
if err != nil {
log.Println("Copy file failed:", err)
return err
}
}
} else {
err := w.WriteField(key, param)
if err != nil {
return err
}
}
}
return nil
}
示例3: SendMediaRequest
func SendMediaRequest(client *twittergo.Client, reqUrl string, params map[string]string, media []byte) (mediaResp twittergo.MediaResponse, err error) {
var (
req *http.Request
resp *twittergo.APIResponse
body io.ReadWriter = bytes.NewBufferString("")
mp *multipart.Writer
writer io.Writer
contentType string
)
mp = multipart.NewWriter(body)
for key, value := range params {
mp.WriteField(key, value)
}
if media != nil {
if writer, err = mp.CreateFormField("media"); err != nil {
return
}
writer.Write(media)
}
contentType = fmt.Sprintf("multipart/form-data;boundary=%v", mp.Boundary())
mp.Close()
if req, err = http.NewRequest("POST", reqUrl, body); err != nil {
return
}
req.Header.Set("Content-Type", contentType)
if resp, err = client.SendRequest(req); err != nil {
return
}
err = resp.Parse(&mediaResp)
return
}
示例4: PostWithMultiPartData
func (r Client) PostWithMultiPartData(req_url string, headers map[string][]string, params map[string][]string, body io.Reader, filename string) (resp *http.Response, err error) {
var buffer *bytes.Buffer = new(bytes.Buffer)
var writer *multipart.Writer = multipart.NewWriter(buffer)
for k, v := range params {
for _, field := range v {
err1 := writer.WriteField(k, field)
if err1 != nil {
err = err1
return
}
}
}
w, err := writer.CreateFormFile("file", filename)
if err != nil {
return
}
_, err = io.Copy(w, body)
if err != nil {
return
}
err = writer.Close()
if err != nil {
return
}
if headers == nil {
headers = make(map[string][]string)
}
headers["Content-Type"] = []string{writer.FormDataContentType()}
return r.Post(req_url, headers, buffer, int64(buffer.Len()))
}
示例5: writeField
func writeField(w multipart.Writer, fieldName string, fieldVal string) error {
if err := w.WriteField(fieldName, fieldVal); err != nil {
message := "Can not write field " + fieldName + " into the request. Reason: " + err.Error()
logging.Logger().Warn(message)
return errors.New(message)
}
return nil
}
示例6: writeFields
func writeFields(mpw *multipart.Writer, fields map[string]string) error {
for k, v := range fields {
err := mpw.WriteField(k, v)
if err != nil {
return err
}
}
return nil
}
示例7: encodeChunkedFirstTransmission
func (a *BuyActivity) encodeChunkedFirstTransmission(log bitwrk.Logger, mwriter *multipart.Writer) (err error) {
part, err := mwriter.CreateFormFile("a32chunks", "a32chunks.bin")
if err != nil {
return
}
log.Printf("Sending work chunk hashes to seller [%v].", *a.tx.WorkerURL)
err = cafs.WriteChunkHashes(a.workFile, part)
if err != nil {
return
}
log.Printf("Sending buyer's secret to seller.")
err = mwriter.WriteField("buyersecret", a.buyerSecret.String())
if err != nil {
return
}
return mwriter.Close()
}
示例8: writeMultipart
/*
* extra.CheckCrc:
* 0: 不进行crc32校验
* 1: 以writeMultipart自动生成crc32的值,进行校验
* 2: 以extra.Crc32的值,进行校验
* other: 和2一样, 以 extra.Crc32的值,进行校验
*/
func writeMultipart(writer *multipart.Writer, uptoken, key string, hasKey bool, extra *PutExtra) (err error) {
if extra == nil {
extra = &PutExtra{}
}
//token
if err = writer.WriteField("token", uptoken); err != nil {
return
}
//key
if hasKey {
if err = writer.WriteField("key", key); err != nil {
return
}
}
// extra.Params
if extra.Params != nil {
for k, v := range extra.Params {
err = writer.WriteField(k, v)
if err != nil {
return
}
}
}
//extra.CheckCrc
if extra.CheckCrc != 0 {
err = writer.WriteField("crc32", strconv.FormatInt(int64(extra.Crc32), 10))
if err != nil {
return
}
}
//file
head := make(textproto.MIMEHeader)
// default the filename is same as key , but ""
var fileName = key
if fileName == "" {
fileName = "filename"
}
head.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="file"; filename="%s"`, escapeQuotes(fileName)))
if extra.MimeType != "" {
head.Set("Content-Type", extra.MimeType)
}
_, err = writer.CreatePart(head)
return err
}
示例9: GetBody
func GetBody() (body io.ReadWriter, header string, err error) {
var (
mp *multipart.Writer
media []byte
writer io.Writer
)
body = bytes.NewBufferString("")
mp = multipart.NewWriter(body)
media, err = ioutil.ReadFile("tweet_media/media.png")
if err != nil {
return
}
mp.WriteField("status", fmt.Sprintf("Hello %v!", time.Now()))
writer, err = mp.CreateFormFile("media[]", "media.png")
if err != nil {
return
}
writer.Write(media)
header = fmt.Sprintf("multipart/form-data;boundary=%v", mp.Boundary())
mp.Close()
return
}
示例10: marshalMap
//Coverts map to a multipart form
func marshalMap(writer *multipart.Writer, m map[string]interface{}) error {
if m == nil {
return nil
}
for k, v := range m {
switch v.(type) {
case uint64:
writer.WriteField(k, strconv.FormatUint(v.(uint64), 10))
case int64:
writer.WriteField(k, strconv.FormatInt(v.(int64), 10))
case int:
writer.WriteField(k, strconv.Itoa(v.(int)))
case string:
writer.WriteField(k, v.(string))
default:
return errors.New("Unrecognizable type to marshal")
}
}
return nil
}
示例11: AddPremiumToHTTPWriter
func AddPremiumToHTTPWriter(writer *multipart.Writer) {
// If you're not PRO, you can't do this, get out
if !CURRENT_USER.IsPro {
return
}
OutputMessage("\n" + term.Green + "Setting pro user attributes..." + term.Reset + "\n")
publish_date, disable_comments, hide_stats, unlisted := GetPremiumInput()
if publish_date != "" {
writer.WriteField("publish_date", publish_date)
}
if disable_comments {
writer.WriteField("disable_comments", "1")
}
if hide_stats {
writer.WriteField("hide_stats", "1")
}
if unlisted {
writer.WriteField("unlisted", "1")
}
}
示例12: PostFile
func PostFile(req_url, path, filename string, start, end, filesize int, params map[string]string) (body string, err error) {
var buffer *bytes.Buffer = bytes.NewBuffer(make([]byte, 0))
var writer *multipart.Writer = multipart.NewWriter(buffer)
for k, v := range params {
err = writer.WriteField(k, v)
if err != nil {
return
}
}
var file *os.File
if file, err = os.OpenFile(path, os.O_RDONLY, 0644); err != nil {
return
}
defer file.Close()
w, err := writer.CreateFormFile("file", filename)
if err != nil {
return
}
var size = end - start + 1
if size == filesize {
_, err = io.Copy(w, file)
if err != nil {
return
}
} else {
var section []byte = make([]byte, size)
var n int
n, err = file.ReadAt(section, int64(start))
if err != nil || n != size {
return
}
var buf *bytes.Buffer = bytes.NewBuffer(make([]byte, 0))
buf.Write(section)
_, err = io.Copy(w, buf)
if err != nil {
return
}
}
writer.Close()
var client *http.Client = new(http.Client)
var req *http.Request
req, err = http.NewRequest("POST", req_url, buffer)
if err != nil {
return
}
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0")
var resp *http.Response
resp, err = client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
body = string(resp_body)
if resp.StatusCode != 200 {
err = errors.New(fmt.Sprintf("%d", resp.StatusCode))
return
}
return
}
示例13: post
func (douban *Douban) post(requestUrl string, accessToken string, params Params, picReader io.Reader, picFormat string, response interface{}) error {
var urlBuffer bytes.Buffer
urlBuffer.WriteString(requestUrl)
var bodyBuffer bytes.Buffer
var writer *multipart.Writer
if picReader == nil {
body := url.Values{}
for k, v := range params {
value := fmt.Sprint(v)
body.Add(k, value)
}
bodyBuffer = *bytes.NewBufferString(body.Encode())
} else {
writer = multipart.NewWriter(&bodyBuffer)
picWriter, err := writer.CreateFormFile("image", "image."+picFormat)
if err != nil {
return err
}
_, e := io.Copy(picWriter, picReader)
if e != nil {
return e
}
for k, v := range params {
value := fmt.Sprint(v)
if k != "" && value != "" {
writer.WriteField(k, value)
}
}
writer.Close()
}
// log.Printf("URL: %s\n", urlBuffer.String())
// log.Printf("Body: %#v\n", bodyBuffer)
req, err := http.NewRequest("POST", urlBuffer.String(), &bodyBuffer)
if err != nil {
return err
}
req.Header.Add("Authorization", accessToken)
if picReader == nil {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
} else {
req.Header.Add("Content-Type", writer.FormDataContentType())
}
// log.Printf("Header: %#V\n", req.Header)
resp, err := douban.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respContent, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 200 {
doubanError := DoubanError{}
err := json.Unmarshal(respContent, &doubanError)
if err != nil {
return err
} else {
return &doubanError
}
}
//log.Printf("==================================\n================================\n%s\n", respContent)
return json.Unmarshal(respContent, &response)
}
示例14: TestHTTPAPI
//.........这里部分代码省略.........
t.FailNow()
}
defer resp.Body.Close()
if body, err = ioutil.ReadAll(resp.Body); err != nil {
t.Errorf("ioutil.ReadAll() error(%v)", err)
t.FailNow()
}
t.Logf("%s", body)
if err = json.Unmarshal(body, tr); err != nil {
t.Errorf("json.Unmarshal() error(%v)", err)
t.FailNow()
}
if tr.Ret != 1 {
t.FailNow()
}
StartApi(s, "localhost:6062")
time.Sleep(1 * time.Second)
t.Log("Upload")
buf.Reset()
w = multipart.NewWriter(buf)
if bw, err = w.CreateFormFile("file", "./test/1.jpg"); err != nil {
t.Errorf("w.CreateFormFile() error(%v)", err)
t.FailNow()
}
if f, err = os.Open("./test/1.jpg"); err != nil {
t.Errorf("os.Open() error(%v)", err)
t.FailNow()
}
defer f.Close()
if _, err = io.Copy(bw, f); err != nil {
t.Errorf("io.Copy() error(%v)", err)
t.FailNow()
}
if err = w.WriteField("vid", "1"); err != nil {
t.Errorf("w.WriteField() error(%v)", err)
t.FailNow()
}
if err = w.WriteField("key", "15"); err != nil {
t.Errorf("w.WriteField() error(%v)", err)
t.FailNow()
}
if err = w.WriteField("cookie", "15"); err != nil {
t.Errorf("w.WriteField() error(%v)", err)
t.FailNow()
}
w.Close()
if req, err = http.NewRequest("POST", "http://localhost:6062/upload", buf); err != nil {
t.Errorf("http..NewRequest() error(%v)", err)
t.FailNow()
}
req.Header.Set("Content-Type", w.FormDataContentType())
if resp, err = client.Do(req); err != nil {
t.Errorf("client.Do() error(%v)", err)
t.FailNow()
}
defer resp.Body.Close()
if body, err = ioutil.ReadAll(resp.Body); err != nil {
t.Errorf("ioutil.ReadAll() error(%v)", err)
t.FailNow()
}
if err = json.Unmarshal(body, tr); err != nil {
t.Errorf("json.Unmarshal() error(%v)", err)
t.FailNow()
}
if tr.Ret != 1 {
t.Errorf("ret: %d", tr.Ret)
示例15: sendPostHttpRequest
// 向微博API服务器发送POST请求
//
// 输入参数的含义请见Upload函数注释。当reader == nil时使用query string模式,否则使用multipart。
func (weibo *Weibo) sendPostHttpRequest(uri string, token string, params Params, reader io.Reader, imageFormat string, response interface{}) error {
// 生成POST请求URI
requestUri := fmt.Sprintf("%s?access_token=%s", uri, token)
// 生成POST内容
var bodyBuffer bytes.Buffer
var writer *multipart.Writer
if reader == nil {
// reader为nil时无文件上传,因此POST body为简单的query string模式
pb := url.Values{}
pb.Add("access_token", token)
for k, v := range params {
value := fmt.Sprint(v)
if k != "" && value != "" {
pb.Add(k, value)
}
}
bodyBuffer = *bytes.NewBufferString(pb.Encode())
} else {
// 否则POST body使用multipart模式
writer = multipart.NewWriter(&bodyBuffer)
imagePartWriter, _ := writer.CreateFormFile("pic", "image."+imageFormat)
io.Copy(imagePartWriter, reader)
for k, v := range params {
value := fmt.Sprint(v)
if k != "" && value != "" {
writer.WriteField(k, value)
}
}
writer.Close()
}
// 生成POST请求
req, err := http.NewRequest("POST", requestUri, &bodyBuffer)
if err != nil {
return err
}
if reader == nil {
// reader为nil时使用一般的内容类型
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
// 否则使用带boundary的multipart类型
req.Header.Set("Content-Type", writer.FormDataContentType())
}
// 发送请求
resp, err := weibo.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// 解析API服务器返回内容
bytes, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode == 200 {
err := json.Unmarshal(bytes, &response)
if err != nil {
return err
}
return nil
} else {
var weiboErr WeiboError
err := json.Unmarshal(bytes, &weiboErr)
if err != nil {
return err
}
return weiboErr
}
return nil
}