httputils.go 3.0 KB

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