httputils.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package httputils
  2. import (
  3. "io"
  4. "mime"
  5. "net/http"
  6. "strings"
  7. "github.com/docker/docker/errdefs"
  8. "github.com/pkg/errors"
  9. "github.com/sirupsen/logrus"
  10. "golang.org/x/net/context"
  11. )
  12. type contextKey string
  13. // APIVersionKey is the client's requested API version.
  14. const APIVersionKey contextKey = "api-version"
  15. // APIFunc is an adapter to allow the use of ordinary functions as Docker API endpoints.
  16. // Any function that has the appropriate signature can be registered as an API endpoint (e.g. getVersion).
  17. type APIFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error
  18. // HijackConnection interrupts the http response writer to get the
  19. // underlying connection and operate with it.
  20. func HijackConnection(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
  21. conn, _, err := w.(http.Hijacker).Hijack()
  22. if err != nil {
  23. return nil, nil, err
  24. }
  25. // Flush the options to make sure the client sets the raw mode
  26. conn.Write([]byte{})
  27. return conn, conn, nil
  28. }
  29. // CloseStreams ensures that a list for http streams are properly closed.
  30. func CloseStreams(streams ...interface{}) {
  31. for _, stream := range streams {
  32. if tcpc, ok := stream.(interface {
  33. CloseWrite() error
  34. }); ok {
  35. tcpc.CloseWrite()
  36. } else if closer, ok := stream.(io.Closer); ok {
  37. closer.Close()
  38. }
  39. }
  40. }
  41. // CheckForJSON makes sure that the request's Content-Type is application/json.
  42. func CheckForJSON(r *http.Request) error {
  43. ct := r.Header.Get("Content-Type")
  44. // No Content-Type header is ok as long as there's no Body
  45. if ct == "" {
  46. if r.Body == nil || r.ContentLength == 0 {
  47. return nil
  48. }
  49. }
  50. // Otherwise it better be json
  51. if matchesContentType(ct, "application/json") {
  52. return nil
  53. }
  54. return errdefs.InvalidParameter(errors.Errorf("Content-Type specified (%s) must be 'application/json'", ct))
  55. }
  56. // ParseForm ensures the request form is parsed even with invalid content types.
  57. // If we don't do this, POST method without Content-type (even with empty body) will fail.
  58. func ParseForm(r *http.Request) error {
  59. if r == nil {
  60. return nil
  61. }
  62. if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  63. return errdefs.InvalidParameter(err)
  64. }
  65. return nil
  66. }
  67. // VersionFromContext returns an API version from the context using APIVersionKey.
  68. // It panics if the context value does not have version.Version type.
  69. func VersionFromContext(ctx context.Context) string {
  70. if ctx == nil {
  71. return ""
  72. }
  73. if val := ctx.Value(APIVersionKey); val != nil {
  74. return val.(string)
  75. }
  76. return ""
  77. }
  78. // matchesContentType validates the content type against the expected one
  79. func matchesContentType(contentType, expectedType string) bool {
  80. mimetype, _, err := mime.ParseMediaType(contentType)
  81. if err != nil {
  82. logrus.Errorf("Error parsing media type: %s error: %v", contentType, err)
  83. }
  84. return err == nil && mimetype == expectedType
  85. }