http.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdhttp
  15. import (
  16. "errors"
  17. "log"
  18. "math"
  19. "net/http"
  20. "strings"
  21. "time"
  22. etcdErr "github.com/coreos/etcd/error"
  23. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  24. "github.com/coreos/etcd/etcdserver/security"
  25. )
  26. const (
  27. // time to wait for response from EtcdServer requests
  28. // 5s for disk and network delay + 10*heartbeat for commit and possible
  29. // leader switch
  30. // TODO: use heartbeat set in etcdserver
  31. defaultServerTimeout = 5*time.Second + 10*(100*time.Millisecond)
  32. // time to wait for a Watch request
  33. defaultWatchTimeout = time.Duration(math.MaxInt64)
  34. )
  35. var errClosed = errors.New("etcdhttp: client closed connection")
  36. // writeError logs and writes the given Error to the ResponseWriter
  37. // If Error is an etcdErr, it is rendered to the ResponseWriter
  38. // Otherwise, it is assumed to be an InternalServerError
  39. func writeError(w http.ResponseWriter, err error) {
  40. if err == nil {
  41. return
  42. }
  43. switch e := err.(type) {
  44. case *etcdErr.Error:
  45. e.WriteTo(w)
  46. case *httptypes.HTTPError:
  47. e.WriteTo(w)
  48. case security.MergeError:
  49. herr := httptypes.NewHTTPError(http.StatusBadRequest, e.Error())
  50. herr.WriteTo(w)
  51. default:
  52. log.Printf("etcdhttp: unexpected error: %v", err)
  53. herr := httptypes.NewHTTPError(http.StatusInternalServerError, "Internal Server Error")
  54. herr.WriteTo(w)
  55. }
  56. }
  57. // allowMethod verifies that the given method is one of the allowed methods,
  58. // and if not, it writes an error to w. A boolean is returned indicating
  59. // whether or not the method is allowed.
  60. func allowMethod(w http.ResponseWriter, m string, ms ...string) bool {
  61. for _, meth := range ms {
  62. if m == meth {
  63. return true
  64. }
  65. }
  66. w.Header().Set("Allow", strings.Join(ms, ","))
  67. http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
  68. return false
  69. }