Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Golang Multipart File Upload Example大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

http://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/


The Go language is one of my favorite programming languages. However,sometimes doing simple things can seem a bit harder than it should. However,most of the time,the problem is just to find out how to do things the easy way. While Go’s documention isn’t bad,the real key to finding out how to do things is often to look at thesource codeand thetest suite.

I’m not yet super familiar with all the std lib packages,so when I wanted to test my Go web services,I wrote a few lines of code to create a multipart file upload function that was building the body from scratch. Once I was done messing with the varIoUs headers,boundary protocol etc.. I started testing some edge cases,I found some bugs in my code. Looking at Go’s packages,I realized that all the tools were already available for me to use. I was just lacking a good example. Walking through the test suite I finally figured out how to write a simple multipart file upload example with some extra query params.

Hopefully this example will be helpful to some of you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main  import (  "bytes"  "fmt"  "io"  "log"  "mime/multipart"  "net/http"  "os"  "path/filepath" )  // Creates a new file upload http request with optional extra params func newfileUploadRequest(uri string, params map[]paramNamepath ) (*http.Requesterror{  fileerr := osOpenpath)  if != nil {  return nilerr  }  defer Close()   body := &bytesBuffer{}  writer multipartNewWriterbody)  partwriterCreateFormFilefilepathBase))  }  _= ioCopy)   for keyval := range params _ WriteFieldval)  ()  }   NewRequest("POST"uri) }  main() Getwd()  path += "/test.pdf"  extraParams {  "title": "My Document" "author""Matt Aimonetti""description""A document with all the Go programming language secrets" request"https://google.com/upload"extraParams"file""/tmp/doc.pdf"logFatalerrclient ClientrespclientDo} else ReadFromBodyfmtPrintlnStatusCodeHeader} } 

Example’s source code on GitHub

All the work is done in thenewfileUploadRequestfunction and really,themime/multipartpackage hides all the complexity of creating a multipart request.

The key is to set a newmultipart.Writer:

1
)

The writer will do all the work and will write directly to our body (which itself is a buffer of bytes).

We then create a part for the file form entry with the name of the file param and the name of the file (that we extracted using thepath/filepathpackage). We need to add the content of the file to the file part,we use theio.copy()to do so. In the first version of this article,I had usedio/IoUtilReadallto read the content of the file (see codehere). However a few readers rightfully mentioned that I should instead copy content from the file to the part instead of temporarily loading the content of the file in memory.Hereis an even more optimized version using goroutine to stream the data,andhereis the full example using a pipe.

1
2
)) ) 

Themultipart.Writertakes care of setting the boundary and formating the form data for us,nice isn’t it?!

Then for any extra params passed as a map of string keys to string value,we use another function of themultipart.Writertype:

 Once again,the writer takes care of creating the right headers,and to add the passed value.

At this point,we just need to close our writer and use our body to create a new request.

() req One last thing before triggering our request,we need to set the header that contains the content type including the boundary being used. Once again,the Go lib has us covered:

Add
"Content-Type"FormDataContentType())

As a reference,here is the generated body:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
--0d940a1e725445cd9192c14c5a3f3d30ea9c90f1f5fb9c08813b3fc2adee Content-Disposition: formdata; name=filename"doc.pdf" Typeapplication/octetstream  %PDF-1.4 %???? 4 0 obj <</Type Catalog // removed for example trailer Size 18 Root R >> startxref 45054 %%EOF "title"  My Document "author"  Matt Aimonetti "description"  A document with all the Go programming language secrets d940a1e725445cd9192c14c5a3f3d30ea9c90f1f5fb9c08813b3fc2adee-- 

Golang might not be as high level as Ruby or Python,but it’s not too far off and it certainly comes with some great std libs. I kNow I recently caught myself writing a lot of small scripts in Go,something I used to do in Ruby. I think this is mainly due to the fact that Go is compiled,designed for concurrency,has great std libs and is quite easy to write.

Hopefully this code sample illustrates how easy Go can be and can also serve as a reference point if you are looking for a way to do multipart upload.

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

猜你在找的Go相关文章

方法和接收者 Go语言中的方法(Method)是一种作用于特定类型变量的函数。这种特定类型变量叫做接收者(Receiver)。接收者的概念就类似于其他语言中的this或者 self。 Go 语言中同时
函数是组织好的、可重复使用的、用于执行指定任务的代码块。 Go语言中支持函数、匿名函数和闭包,并且函数在Go语言中属于“一等公民”。 函数定义 Go语言中定义函数使用func关键字,具体格式如下: f
面向对象的三大特征: 封装:隐藏对象的属性和实现细节,仅对外提供公共访问方式 继承:使得子类具有父类的属性和方法或者重新定义、追加属性和方法等 多态:不同对象中同种行为的不同实现方式 Go并不是一个纯
在工程化的开发项目中,Go语言的源码复用是建立在包(package)基础之上的。 包(package)是多个Go源码的集合,是一种高级的代码复用方案,Go语言提供了很多内置包,如fmt、os、io等。
为什么要学 Go 性能优越感;Go 极其地快,其性能与 Java 或 C++相似。在使用中,Go 一般比 Python 要快 30 倍; 序列化/去序列化、排序和聚合中表现优异; 开发者效率较高;多种
什么是反射 官方关于反射定义: Reflection in computing is the ability of a program to examine its own structure, pa
因为数组的长度是固定的并且数组长度属于类型的一部分,所以数组有很多的局限性。 func arraySum(x [3]int) int{ sum := 0 for _, v := range x{ su
接口(interface)定义了一个对象的行为规范,只定义规范不实现,由具体的对象来实现规范的细节。 接口类型 在Go语言中接口(interface)是一种类型,一种抽象的类型。 interface是

大佬总结

以上是大佬教程为你收集整理的Golang Multipart File Upload Example全部内容,希望文章能够帮你解决Golang Multipart File Upload Example所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: