本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

211 lines
6.0KB

  1. // Copyright 2011 Google Inc. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. // Package urlfetch provides an http.RoundTripper implementation
  5. // for fetching URLs via App Engine's urlfetch service.
  6. package urlfetch // import "google.golang.org/appengine/urlfetch"
  7. import (
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "net/http"
  13. "net/url"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/golang/protobuf/proto"
  18. "golang.org/x/net/context"
  19. "google.golang.org/appengine/internal"
  20. pb "google.golang.org/appengine/internal/urlfetch"
  21. )
  22. // Transport is an implementation of http.RoundTripper for
  23. // App Engine. Users should generally create an http.Client using
  24. // this transport and use the Client rather than using this transport
  25. // directly.
  26. type Transport struct {
  27. Context context.Context
  28. // Controls whether the application checks the validity of SSL certificates
  29. // over HTTPS connections. A value of false (the default) instructs the
  30. // application to send a request to the server only if the certificate is
  31. // valid and signed by a trusted certificate authority (CA), and also
  32. // includes a hostname that matches the certificate. A value of true
  33. // instructs the application to perform no certificate validation.
  34. AllowInvalidServerCertificate bool
  35. }
  36. // Verify statically that *Transport implements http.RoundTripper.
  37. var _ http.RoundTripper = (*Transport)(nil)
  38. // Client returns an *http.Client using a default urlfetch Transport. This
  39. // client will have the default deadline of 5 seconds, and will check the
  40. // validity of SSL certificates.
  41. //
  42. // Any deadline of the provided context will be used for requests through this client;
  43. // if the client does not have a deadline then a 5 second default is used.
  44. func Client(ctx context.Context) *http.Client {
  45. return &http.Client{
  46. Transport: &Transport{
  47. Context: ctx,
  48. },
  49. }
  50. }
  51. type bodyReader struct {
  52. content []byte
  53. truncated bool
  54. closed bool
  55. }
  56. // ErrTruncatedBody is the error returned after the final Read() from a
  57. // response's Body if the body has been truncated by App Engine's proxy.
  58. var ErrTruncatedBody = errors.New("urlfetch: truncated body")
  59. func statusCodeToText(code int) string {
  60. if t := http.StatusText(code); t != "" {
  61. return t
  62. }
  63. return strconv.Itoa(code)
  64. }
  65. func (br *bodyReader) Read(p []byte) (n int, err error) {
  66. if br.closed {
  67. if br.truncated {
  68. return 0, ErrTruncatedBody
  69. }
  70. return 0, io.EOF
  71. }
  72. n = copy(p, br.content)
  73. if n > 0 {
  74. br.content = br.content[n:]
  75. return
  76. }
  77. if br.truncated {
  78. br.closed = true
  79. return 0, ErrTruncatedBody
  80. }
  81. return 0, io.EOF
  82. }
  83. func (br *bodyReader) Close() error {
  84. br.closed = true
  85. br.content = nil
  86. return nil
  87. }
  88. // A map of the URL Fetch-accepted methods that take a request body.
  89. var methodAcceptsRequestBody = map[string]bool{
  90. "POST": true,
  91. "PUT": true,
  92. "PATCH": true,
  93. }
  94. // urlString returns a valid string given a URL. This function is necessary because
  95. // the String method of URL doesn't correctly handle URLs with non-empty Opaque values.
  96. // See http://code.google.com/p/go/issues/detail?id=4860.
  97. func urlString(u *url.URL) string {
  98. if u.Opaque == "" || strings.HasPrefix(u.Opaque, "//") {
  99. return u.String()
  100. }
  101. aux := *u
  102. aux.Opaque = "//" + aux.Host + aux.Opaque
  103. return aux.String()
  104. }
  105. // RoundTrip issues a single HTTP request and returns its response. Per the
  106. // http.RoundTripper interface, RoundTrip only returns an error if there
  107. // was an unsupported request or the URL Fetch proxy fails.
  108. // Note that HTTP response codes such as 5xx, 403, 404, etc are not
  109. // errors as far as the transport is concerned and will be returned
  110. // with err set to nil.
  111. func (t *Transport) RoundTrip(req *http.Request) (res *http.Response, err error) {
  112. methNum, ok := pb.URLFetchRequest_RequestMethod_value[req.Method]
  113. if !ok {
  114. return nil, fmt.Errorf("urlfetch: unsupported HTTP method %q", req.Method)
  115. }
  116. method := pb.URLFetchRequest_RequestMethod(methNum)
  117. freq := &pb.URLFetchRequest{
  118. Method: &method,
  119. Url: proto.String(urlString(req.URL)),
  120. FollowRedirects: proto.Bool(false), // http.Client's responsibility
  121. MustValidateServerCertificate: proto.Bool(!t.AllowInvalidServerCertificate),
  122. }
  123. if deadline, ok := t.Context.Deadline(); ok {
  124. freq.Deadline = proto.Float64(deadline.Sub(time.Now()).Seconds())
  125. }
  126. for k, vals := range req.Header {
  127. for _, val := range vals {
  128. freq.Header = append(freq.Header, &pb.URLFetchRequest_Header{
  129. Key: proto.String(k),
  130. Value: proto.String(val),
  131. })
  132. }
  133. }
  134. if methodAcceptsRequestBody[req.Method] && req.Body != nil {
  135. // Avoid a []byte copy if req.Body has a Bytes method.
  136. switch b := req.Body.(type) {
  137. case interface {
  138. Bytes() []byte
  139. }:
  140. freq.Payload = b.Bytes()
  141. default:
  142. freq.Payload, err = ioutil.ReadAll(req.Body)
  143. if err != nil {
  144. return nil, err
  145. }
  146. }
  147. }
  148. fres := &pb.URLFetchResponse{}
  149. if err := internal.Call(t.Context, "urlfetch", "Fetch", freq, fres); err != nil {
  150. return nil, err
  151. }
  152. res = &http.Response{}
  153. res.StatusCode = int(*fres.StatusCode)
  154. res.Status = fmt.Sprintf("%d %s", res.StatusCode, statusCodeToText(res.StatusCode))
  155. res.Header = make(http.Header)
  156. res.Request = req
  157. // Faked:
  158. res.ProtoMajor = 1
  159. res.ProtoMinor = 1
  160. res.Proto = "HTTP/1.1"
  161. res.Close = true
  162. for _, h := range fres.Header {
  163. hkey := http.CanonicalHeaderKey(*h.Key)
  164. hval := *h.Value
  165. if hkey == "Content-Length" {
  166. // Will get filled in below for all but HEAD requests.
  167. if req.Method == "HEAD" {
  168. res.ContentLength, _ = strconv.ParseInt(hval, 10, 64)
  169. }
  170. continue
  171. }
  172. res.Header.Add(hkey, hval)
  173. }
  174. if req.Method != "HEAD" {
  175. res.ContentLength = int64(len(fres.Content))
  176. }
  177. truncated := fres.GetContentWasTruncated()
  178. res.Body = &bodyReader{content: fres.Content, truncated: truncated}
  179. return
  180. }
  181. func init() {
  182. internal.RegisterErrorCodeMap("urlfetch", pb.URLFetchServiceError_ErrorCode_name)
  183. internal.RegisterTimeoutErrorCode("urlfetch", int32(pb.URLFetchServiceError_DEADLINE_EXCEEDED))
  184. }
上海开阖软件有限公司 沪ICP备12045867号-1