Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

350 Zeilen
11 KiB

  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gensupport
  5. import (
  6. "bytes"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "mime/multipart"
  11. "net/http"
  12. "net/textproto"
  13. "strings"
  14. "sync"
  15. "google.golang.org/api/googleapi"
  16. )
  17. const sniffBuffSize = 512
  18. func newContentSniffer(r io.Reader) *contentSniffer {
  19. return &contentSniffer{r: r}
  20. }
  21. // contentSniffer wraps a Reader, and reports the content type determined by sniffing up to 512 bytes from the Reader.
  22. type contentSniffer struct {
  23. r io.Reader
  24. start []byte // buffer for the sniffed bytes.
  25. err error // set to any error encountered while reading bytes to be sniffed.
  26. ctype string // set on first sniff.
  27. sniffed bool // set to true on first sniff.
  28. }
  29. func (cs *contentSniffer) Read(p []byte) (n int, err error) {
  30. // Ensure that the content type is sniffed before any data is consumed from Reader.
  31. _, _ = cs.ContentType()
  32. if len(cs.start) > 0 {
  33. n := copy(p, cs.start)
  34. cs.start = cs.start[n:]
  35. return n, nil
  36. }
  37. // We may have read some bytes into start while sniffing, even if the read ended in an error.
  38. // We should first return those bytes, then the error.
  39. if cs.err != nil {
  40. return 0, cs.err
  41. }
  42. // Now we have handled all bytes that were buffered while sniffing. Now just delegate to the underlying reader.
  43. return cs.r.Read(p)
  44. }
  45. // ContentType returns the sniffed content type, and whether the content type was succesfully sniffed.
  46. func (cs *contentSniffer) ContentType() (string, bool) {
  47. if cs.sniffed {
  48. return cs.ctype, cs.ctype != ""
  49. }
  50. cs.sniffed = true
  51. // If ReadAll hits EOF, it returns err==nil.
  52. cs.start, cs.err = ioutil.ReadAll(io.LimitReader(cs.r, sniffBuffSize))
  53. // Don't try to detect the content type based on possibly incomplete data.
  54. if cs.err != nil {
  55. return "", false
  56. }
  57. cs.ctype = http.DetectContentType(cs.start)
  58. return cs.ctype, true
  59. }
  60. // DetermineContentType determines the content type of the supplied reader.
  61. // If the content type is already known, it can be specified via ctype.
  62. // Otherwise, the content of media will be sniffed to determine the content type.
  63. // If media implements googleapi.ContentTyper (deprecated), this will be used
  64. // instead of sniffing the content.
  65. // After calling DetectContentType the caller must not perform further reads on
  66. // media, but rather read from the Reader that is returned.
  67. func DetermineContentType(media io.Reader, ctype string) (io.Reader, string) {
  68. // Note: callers could avoid calling DetectContentType if ctype != "",
  69. // but doing the check inside this function reduces the amount of
  70. // generated code.
  71. if ctype != "" {
  72. return media, ctype
  73. }
  74. // For backwards compatability, allow clients to set content
  75. // type by providing a ContentTyper for media.
  76. if typer, ok := media.(googleapi.ContentTyper); ok {
  77. return media, typer.ContentType()
  78. }
  79. sniffer := newContentSniffer(media)
  80. if ctype, ok := sniffer.ContentType(); ok {
  81. return sniffer, ctype
  82. }
  83. // If content type could not be sniffed, reads from sniffer will eventually fail with an error.
  84. return sniffer, ""
  85. }
  86. type typeReader struct {
  87. io.Reader
  88. typ string
  89. }
  90. // multipartReader combines the contents of multiple readers to create a multipart/related HTTP body.
  91. // Close must be called if reads from the multipartReader are abandoned before reaching EOF.
  92. type multipartReader struct {
  93. pr *io.PipeReader
  94. ctype string
  95. mu sync.Mutex
  96. pipeOpen bool
  97. }
  98. func newMultipartReader(parts []typeReader) *multipartReader {
  99. mp := &multipartReader{pipeOpen: true}
  100. var pw *io.PipeWriter
  101. mp.pr, pw = io.Pipe()
  102. mpw := multipart.NewWriter(pw)
  103. mp.ctype = "multipart/related; boundary=" + mpw.Boundary()
  104. go func() {
  105. for _, part := range parts {
  106. w, err := mpw.CreatePart(typeHeader(part.typ))
  107. if err != nil {
  108. mpw.Close()
  109. pw.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", err))
  110. return
  111. }
  112. _, err = io.Copy(w, part.Reader)
  113. if err != nil {
  114. mpw.Close()
  115. pw.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", err))
  116. return
  117. }
  118. }
  119. mpw.Close()
  120. pw.Close()
  121. }()
  122. return mp
  123. }
  124. func (mp *multipartReader) Read(data []byte) (n int, err error) {
  125. return mp.pr.Read(data)
  126. }
  127. func (mp *multipartReader) Close() error {
  128. mp.mu.Lock()
  129. if !mp.pipeOpen {
  130. mp.mu.Unlock()
  131. return nil
  132. }
  133. mp.pipeOpen = false
  134. mp.mu.Unlock()
  135. return mp.pr.Close()
  136. }
  137. // CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body.
  138. // It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary.
  139. //
  140. // The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF.
  141. func CombineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType string) (io.ReadCloser, string) {
  142. mp := newMultipartReader([]typeReader{
  143. {body, bodyContentType},
  144. {media, mediaContentType},
  145. })
  146. return mp, mp.ctype
  147. }
  148. func typeHeader(contentType string) textproto.MIMEHeader {
  149. h := make(textproto.MIMEHeader)
  150. if contentType != "" {
  151. h.Set("Content-Type", contentType)
  152. }
  153. return h
  154. }
  155. // PrepareUpload determines whether the data in the supplied reader should be
  156. // uploaded in a single request, or in sequential chunks.
  157. // chunkSize is the size of the chunk that media should be split into.
  158. //
  159. // If chunkSize is zero, media is returned as the first value, and the other
  160. // two return values are nil, true.
  161. //
  162. // Otherwise, a MediaBuffer is returned, along with a bool indicating whether the
  163. // contents of media fit in a single chunk.
  164. //
  165. // After PrepareUpload has been called, media should no longer be used: the
  166. // media content should be accessed via one of the return values.
  167. func PrepareUpload(media io.Reader, chunkSize int) (r io.Reader, mb *MediaBuffer, singleChunk bool) {
  168. if chunkSize == 0 { // do not chunk
  169. return media, nil, true
  170. }
  171. mb = NewMediaBuffer(media, chunkSize)
  172. _, _, _, err := mb.Chunk()
  173. // If err is io.EOF, we can upload this in a single request. Otherwise, err is
  174. // either nil or a non-EOF error. If it is the latter, then the next call to
  175. // mb.Chunk will return the same error. Returning a MediaBuffer ensures that this
  176. // error will be handled at some point.
  177. return nil, mb, err == io.EOF
  178. }
  179. // MediaInfo holds information for media uploads. It is intended for use by generated
  180. // code only.
  181. type MediaInfo struct {
  182. // At most one of Media and MediaBuffer will be set.
  183. media io.Reader
  184. buffer *MediaBuffer
  185. singleChunk bool
  186. mType string
  187. size int64 // mediaSize, if known. Used only for calls to progressUpdater_.
  188. progressUpdater googleapi.ProgressUpdater
  189. }
  190. // NewInfoFromMedia should be invoked from the Media method of a call. It returns a
  191. // MediaInfo populated with chunk size and content type, and a reader or MediaBuffer
  192. // if needed.
  193. func NewInfoFromMedia(r io.Reader, options []googleapi.MediaOption) *MediaInfo {
  194. mi := &MediaInfo{}
  195. opts := googleapi.ProcessMediaOptions(options)
  196. if !opts.ForceEmptyContentType {
  197. r, mi.mType = DetermineContentType(r, opts.ContentType)
  198. }
  199. mi.media, mi.buffer, mi.singleChunk = PrepareUpload(r, opts.ChunkSize)
  200. return mi
  201. }
  202. // NewInfoFromResumableMedia should be invoked from the ResumableMedia method of a
  203. // call. It returns a MediaInfo using the given reader, size and media type.
  204. func NewInfoFromResumableMedia(r io.ReaderAt, size int64, mediaType string) *MediaInfo {
  205. rdr := ReaderAtToReader(r, size)
  206. rdr, mType := DetermineContentType(rdr, mediaType)
  207. return &MediaInfo{
  208. size: size,
  209. mType: mType,
  210. buffer: NewMediaBuffer(rdr, googleapi.DefaultUploadChunkSize),
  211. media: nil,
  212. singleChunk: false,
  213. }
  214. }
  215. // SetProgressUpdater sets the progress updater for the media info.
  216. func (mi *MediaInfo) SetProgressUpdater(pu googleapi.ProgressUpdater) {
  217. if mi != nil {
  218. mi.progressUpdater = pu
  219. }
  220. }
  221. // UploadType determines the type of upload: a single request, or a resumable
  222. // series of requests.
  223. func (mi *MediaInfo) UploadType() string {
  224. if mi.singleChunk {
  225. return "multipart"
  226. }
  227. return "resumable"
  228. }
  229. // UploadRequest sets up an HTTP request for media upload. It adds headers
  230. // as necessary, and returns a replacement for the body and a function for http.Request.GetBody.
  231. func (mi *MediaInfo) UploadRequest(reqHeaders http.Header, body io.Reader) (newBody io.Reader, getBody func() (io.ReadCloser, error), cleanup func()) {
  232. cleanup = func() {}
  233. if mi == nil {
  234. return body, nil, cleanup
  235. }
  236. var media io.Reader
  237. if mi.media != nil {
  238. // This only happens when the caller has turned off chunking. In that
  239. // case, we write all of media in a single non-retryable request.
  240. media = mi.media
  241. } else if mi.singleChunk {
  242. // The data fits in a single chunk, which has now been read into the MediaBuffer.
  243. // We obtain that chunk so we can write it in a single request. The request can
  244. // be retried because the data is stored in the MediaBuffer.
  245. media, _, _, _ = mi.buffer.Chunk()
  246. }
  247. if media != nil {
  248. fb := readerFunc(body)
  249. fm := readerFunc(media)
  250. combined, ctype := CombineBodyMedia(body, "application/json", media, mi.mType)
  251. if fb != nil && fm != nil {
  252. getBody = func() (io.ReadCloser, error) {
  253. rb := ioutil.NopCloser(fb())
  254. rm := ioutil.NopCloser(fm())
  255. r, _ := CombineBodyMedia(rb, "application/json", rm, mi.mType)
  256. return r, nil
  257. }
  258. }
  259. cleanup = func() { combined.Close() }
  260. reqHeaders.Set("Content-Type", ctype)
  261. body = combined
  262. }
  263. if mi.buffer != nil && mi.mType != "" && !mi.singleChunk {
  264. reqHeaders.Set("X-Upload-Content-Type", mi.mType)
  265. }
  266. return body, getBody, cleanup
  267. }
  268. // readerFunc returns a function that always returns an io.Reader that has the same
  269. // contents as r, provided that can be done without consuming r. Otherwise, it
  270. // returns nil.
  271. // See http.NewRequest (in net/http/request.go).
  272. func readerFunc(r io.Reader) func() io.Reader {
  273. switch r := r.(type) {
  274. case *bytes.Buffer:
  275. buf := r.Bytes()
  276. return func() io.Reader { return bytes.NewReader(buf) }
  277. case *bytes.Reader:
  278. snapshot := *r
  279. return func() io.Reader { r := snapshot; return &r }
  280. case *strings.Reader:
  281. snapshot := *r
  282. return func() io.Reader { r := snapshot; return &r }
  283. default:
  284. return nil
  285. }
  286. }
  287. // ResumableUpload returns an appropriately configured ResumableUpload value if the
  288. // upload is resumable, or nil otherwise.
  289. func (mi *MediaInfo) ResumableUpload(locURI string) *ResumableUpload {
  290. if mi == nil || mi.singleChunk {
  291. return nil
  292. }
  293. return &ResumableUpload{
  294. URI: locURI,
  295. Media: mi.buffer,
  296. MediaType: mi.mType,
  297. Callback: func(curr int64) {
  298. if mi.progressUpdater != nil {
  299. mi.progressUpdater(curr, mi.size)
  300. }
  301. },
  302. }
  303. }
  304. // SetGetBody sets the GetBody field of req to f. This was once needed
  305. // to gracefully support Go 1.7 and earlier which didn't have that
  306. // field.
  307. //
  308. // Deprecated: the code generator no longer uses this as of
  309. // 2019-02-19. Nothing else should be calling this anyway, but we
  310. // won't delete this immediately; it will be deleted in as early as 6
  311. // months.
  312. func SetGetBody(req *http.Request, f func() (io.ReadCloser, error)) {
  313. req.GetBody = f
  314. }